Tar
Tar

Reputation: 9015

How to serve create-react-app from Flask?

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).

Upvotes: 1

Views: 1878

Answers (1)

v25
v25

Reputation: 7621

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.

Upvotes: 1

Related Questions