It is not recommended to server static files through Flask app, you have to configure your web server to do that. However If you still need to serve static files through your Flask app, here is the way how to do that.
There is a function called “send_from_directory” which can take a file from given path and return.Let’s use it
send_from_directory( <FilePath>, <FileName> )
- Import Modules
from flask import send_from_directory
- Creating route
@app.route('/js/<filename>')
def js_files(path):
return send_from_directory('js', path)
@app.route('/css/<filename>')
def css_files(path):
return send_from_directory('css', path)
@app.route('/images/<filename>')
def image_files(path):
return send_from_directory('images', path)
Here I have implemented three routes for serving js, css and images. Replace ‘js’ , ‘css’, ‘images’ with your static file paths.