Python Flask Serve Static Files (Images, JS, CSS, etc.)

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
def js_files(path):
    return send_from_directory('js', path)

def css_files(path):
    return send_from_directory('css', path)

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.

Leave a Reply

(*) Required, Your email will not be published