Flask:如何在蓝图中使用app context? [英] Flask: How to use app context inside blueprints?
问题描述
我正在学习烧瓶和python,无法围绕一个典型的烧瓶应用程序的结构。
我需要从蓝图内部访问应用程序配置。像这样
#blueprint.py
from flask import蓝图
sample_blueprint =蓝图(sample,__name__)
#为此蓝图定义一条路线
@ sample_blueprint.route(/)
def index():
#这是有问题的行
#需要从应用程序访问一些配置
x = app.config [SOMETHING]
#如何访问蓝图内的应用程序?
如果在blueprint中导入应用程序是解决方案,这是否会导致循环导入?即在应用程序中导入蓝图,在蓝图中导入应用程序?
从文档 appcontext :
$ b
应用程序上下文是什么力量 current_app 上下文本地
适用于您的示例:
from flask导入Blueprint,current_app
$ b sample = Blueprint('sample',__name__)
@sample .route('/')
def index():
x = current_app.config ['SOMETHING']
这里是一个小的 gist 我把它放在一起在评论中提到。
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?
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.
这篇关于Flask:如何在蓝图中使用app context?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!