Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static files located under Flask blueprint folder

Tags:

python

flask

I have a Flask blueprint that contains templates and static files. The template is rendered correctly but the linked CSS file returns 404 not found. How do I serve static files that are located under a blueprint's folder?

app/
  __init__.py
  auth/
    __init__.py
    static/
      style.css
    templates/
      index.html
auth = Blueprint('auth', __name__, template_folder='templates')

@auth.route('/')
def index():
    return render_template('index.html')
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
like image 246
Stephen Avatar asked Jan 05 '17 11:01

Stephen


People also ask

Where do I put static files in a Flask?

To use static files in a Flask application, create a folder called static in your package or next to your module and it will be available at /static on the application. app.py is a basic example of Flask with template rendering.

What should be in a static folder Flask?

Folder structure for a Flask app That folder contains two folders, specifically named static and templates. The static folder contains assets used by the templates, including CSS files, JavaScript files, and images.

How do you use blueprints in Flask?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() .


1 Answers

Tell the blueprint where its static folder is by passing static_folder, then use url_for to generate urls to the static route on the blueprint. This is described in the docs.

auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
url_for('auth.static', filename='style.css')

This solution only works if the blueprint has a url_prefix. As per the docs:

However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.

In this case, one solution might be to put the stylesheet into the main static directory.

like image 92
davidism Avatar answered Sep 21 '22 03:09

davidism