Appearance
How to serve static files in Flask
Flask automatically serves static files from a static folder in your project directory. If you need to serve a specific file or use a custom route, you can use the send_from_directory function or app.send_static_file().
Here's an example of how to serve a static file called myfile.txt that is stored in the static folder:
Custom route for static files
python
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)
if __name__ == '__main__':
app.run(debug=True)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
You can then access the file at http://localhost:5000/static/myfile.txt.
Generating URLs with url_for
You can also use the url_for function to generate a URL for a static file. For example:
python
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return url_for('static', filename='myfile.txt')This will return the URL path /static/myfile.txt. Note that send_from_directory safely prevents directory traversal by default. The url_for result is typically used in HTML templates rather than returned directly from a route function.