Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Multiple blueprints interfere with each other

Tags:

python

flask

I'm testing out Flask with blueprints. My app has two blueprints:

  1. base
  2. opinions

base/__init__.py

base = Blueprint('base', __name__, static_folder='static', template_folder='templates') 
#http://server.com/base

opinions/__init__.py

opinions = Blueprint('opinions', __name__, static_folder='static', template_folder='templates')
#http://server.com/opinions

__init__.py

app = Flask(__name__)
from app.base import views 
from app.base import base
app.register_blueprint(base, url_prefix='/base')

from app.opinions import views
from app.opinions import opinions
#app.register_blueprint(opinions, url_prefix='/opinions')  <-- Uncommenting this line causes issues

If I register only 1 of these blueprints, everything runs fine. However, if I register both blueprints, templates are always loaded from opinions. For example if I hit http://server.com/base , the index.html gets picked from opinions folder. Flask documentation does not mention anything about 'template_folder' namespace conflicts.

PS - I would like to know alternative ways of handling multiple blueprints. I'm not very comfortable importing views file from two different blueprints. Whats the better way to do this?

like image 465
Neo Avatar asked Mar 05 '14 07:03

Neo


1 Answers

Blueprint template directories are registered globally. They share one namespace so that your app can override the blueprint's template if necessary. This is mentioned briedly in the documentation.

Thus, you should not name your opinions' template index.html, but rather opinions/index.html. That makes for awkward paths at first glance (…/opinions/templates/opinions/…) but adds flexibility for customizing "canned" templates without changing the blueprint's contents.

like image 161
Matthias Urlichs Avatar answered Sep 21 '22 04:09

Matthias Urlichs