Flask: How to use app context inside blueprints?
·
Answer a question
I'm learning flask and python and cannot wrap my head around the way a typical flask application needs to be structured.
I need to access the app config from inside blueprint. Something like this
#blueprint.py
from flask import Blueprint
sample_blueprint = Blueprint("sample", __name__)
# defining a route for this blueprint
@sample_blueprint.route("/")
def index():
# !this is the problematic line
# need to access some config from the app
x = app.config["SOMETHING"]
# how to access app inside blueprint?
If importing app in blueprint is the solution, will this not result in circulat imports? i.e importing blueprint in app, importing app in blueprints?
Answers
From the docs about appcontext:
The application context is what powers the current_app context local
Applied to your example:
from flask import Blueprint, current_app
sample = Blueprint('sample', __name__)
@sample.route('/')
def index():
x = current_app.config['SOMETHING']
For reference here is a small gist I put together, as mentioned in the comments.
更多推荐

所有评论(0)