1

How can I serve the deliverables of create-react-app via Flask?

After npm run build, this is roughly my folder tree:

src/
├── service/
│   └── app.py
└── content/
    ├── static
    │   ├── css
    │   │   └── many css files...
    │   ├── js
    │   │   └── many js files...
    │   └── media
    │       └── some images...
    ├── index.html
    ├── service-worker.js
    └── manifest.json

That's the server's code:

app = Flask(__name__, template_folder='../content', static_folder='../content')

@app.route('/')
def home():
    return flask.render_template('index.html')

@app.route('/static/<path:path>')
def static_files(path):
    return flask.send_from_directory('../content/static', path)

if __name__ == '__main__':
    app.run(debug=True)

The main html, index.html is served successfully. So are all the files under content/static/.

The files under content/ however (except index.html), are not delivered at all (error 404, not found).

2
  • Are you sure the directory listing you gave is correct. The flask code mentions a build/ directory but this doesn't appear in the directory listing? Commented Jan 15, 2020 at 17:18
  • @v25, thanks, I updated the question (and also double-checked it in my own environment). Commented Jan 15, 2020 at 17:25

1 Answer 1

1

Assuming you're just trying to serve a bunch of static files, that could probably be done more efficiently with a webserver like nginx.

However if you do wish to use Flask, the simplest way to do this with your exisiting directory structure is:

from flask import Flask, render_template

app = Flask(__name__,
            static_url_path='', 
            static_folder='../content')

@app.route('/')
def index_redir():
    # Reached if the user hits example.com/ instead of example.com/index.html
    return render_template('index.html')

This essentially serves everything in the contents/ directory statically at the / endpoint (thanks to the static_url_path being set to an empty string)

Of course there's also the index_redir function which will render index.html if the user actually hits example.com/ instead of example.com/index.html.

This also avoids defining the static_files function from your code, as flask has the functionality to serve static files out of the box.

Again this stuff is probably better suited to nginx in a production env.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked once I added template_folder='../content'. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.