How to serve static files in Flask

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

Alternatively, you could use app.send_file or app.send_static_file, but this is highly discouraged as it can lead to security risks with user-supplied paths; send_from_directory was designed to control those risks.

Leave a Comment