Neo
Neo

Reputation: 13881

Flask: Multiple blueprints interfere with each other

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?

Upvotes: 8

Views: 7377

Answers (1)

Matthias Urlichs
Matthias Urlichs

Reputation: 2524

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.

Upvotes: 9

Related Questions