Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask blueprint static directory does not work?

Tags:

python

flask

According to the Flask readme, blueprint static files are accessible at blueprintname/static. But for some reason, it doesn't work.

My blueprint is like this:

  • app/frontend/views.py :

    frontend = Blueprint('frontend', __name__,                       template_folder='templates',                      static_folder='static')  @frontend.route('/') etc... 
  • app/frontend/js/app.js : my javascript

  • Blueprint registered in Flask app (routes work and everything)

When I go to abc.com/frontend/static/js/app.js, it just gives a 404.

When I follow the Flask readme to get my static files:

<script src="{{url_for('frontend.static', filename='js/app.js')}}"></script> 

The output is

<script src="/static/js/app.js"></script> 

Which doesn't work either. There's nothing in my root app/static/ folder.

I can't access any static files in my blueprint! Flask read me says that it should work!

admin = Blueprint('admin', __name__, static_folder='static') 

By default the rightmost part of the path is where it is exposed on the web. Because the folder is called static here it will be available at the location of the blueprint + /static. Say the blueprint is registered for /admin the static folder will be at /admin/static.

like image 282
Patrick Yan Avatar asked Mar 03 '14 17:03

Patrick Yan


2 Answers

I include an argument to the static_url_path parameter to ensure that the Blueprint's static path doesn't conflict with the static path of the main app.

e.g:

admin = Blueprint('admin', __name__, static_folder='static', static_url_path='/static/admin') 
like image 52
brasqueychutter Avatar answered Sep 23 '22 06:09

brasqueychutter


You probably registered your Blueprint to sit at the root of your site:

app.register_blueprint(core, url_prefix='') 

but the static view in the Blueprint is no different from all your other Blueprint views; it uses that url_prefix value to make the URL unique.

The core static view is also active, so you now have two routes that want to handle /static/ URLs. So if you are registering your Blueprint without a URL prefix, you have to give one of these two a unique path.

Either give the Blueprint a custom static_url_path value, or the core Flask app.

like image 27
Martijn Pieters Avatar answered Sep 21 '22 06:09

Martijn Pieters