Sometimes, we want to serve static files in Python Flask.
In this article, we’ll look at how to serve static files in Python Flask.
How to serve static files in Flask?
To serve static files in Python Flask, we can use the send_from_directory
function.
For instance, we write
from flask import send_from_directory
@app.route('/file/<path:path>')
def send_file(path):
return send_from_directory('file', path)
to call send_from_directory
with the directory and path of the file to return the file as the response when we go to /file/
.
send_from_directory
can safely handle paths for files under a known directory.
Conclusion
To serve static files in Python Flask, we can use the send_from_directory
function.