How to serve static files in Flask
So this is embarrassing. I've got an application that I threw together in
Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation
Flask describes returning static files. Yes, I could use
render_template but I know the data is not templatized. I'd have thought
url_for was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a
Response with appropriate mimetype:
Someone want to give a code sample or url for this? I know this is going to be dead simple.
The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask.
However, you can use
send_from_directory to send files from a directory, which can be pretty convenient in some situations:
from flask import Flask, request, send_from_directory # set the project root directory as the static folder, you can set others. app = Flask(__name__, static_url_path='') @app.route('/js/<path:path>') def send_js(path): return send_from_directory('js', path) if __name__ == "__main__": app.run()
Do not use
send_static_file with an user-supplied path.
from flask import Flask, request # set the project root directory as the static folder, you can set others. app = Flask(__name__, static_url_path='') @app.route('/') def root(): return app.send_static_file('index.html')
★ Back to homepage or read more recommendations: