How to serve static files in Flask

To serve static files in Flask, you will need to use the send_static_file method in your route function.

Here's an example of how to serve a static file called myfile.txt that is stored in the static folder:

from flask import Flask, send_from_directory
app = Flask(__name__)

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

Watch a course Python - The Practical Guide

You can then access the file at http://localhost:5000/static/myfile.txt.

If you want to serve all static files from a folder, you can use the static route decorator.

For example:

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

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

You can then access the file at http://localhost:5000/static/myfile.txt.

You can also use the url_for function to generate a URL for a static file. For example:

from flask import url_for

@app.route('/')
def index():
    return url_for('static', filename='myfile.txt')

This will generate a URL for the myfile.txt file that you can use in your HTML, such as /static/myfile.txt.