Stephen
Stephen

Reputation: 309

Serve static files located under Flask blueprint folder

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') }}">

Upvotes: 6

Views: 4187

Answers (1)

davidism
davidism

Reputation: 127390

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.

Upvotes: 10

Related Questions