访问在应用程序工厂中定义的Flask扩展 [英] Access a Flask extension that is defined in the app factory
问题描述
我正在使用应用程序工厂模式来设置我的Flask应用程序.我的应用程序使用Flask-Babel扩展程序,该扩展程序也是在工厂中设置的.但是,我想以蓝图的形式访问扩展名,以使用它,
I am using the app factory pattern to set up my Flask application. My app uses the Flask-Babel extension, and that is set up in the factory as well. However, I want to access the extension in a blueprint in order to use it,
工厂在__init__.py
.
def create_app(object_name):
app = Flask(__name__)
app.config.from_object(object_name)
babel = Babel(app)
app.register_blueprint(main_blueprint)
app.register_blueprint(category_blueprint)
app.register_blueprint(item_blueprint)
db.init_app(app)
return app
我想在main.py
中添加以下内容:
I want to add the following to main.py
:
@babel.localeselector
def get_locale():
if 'locale' in session:
return session['locale']
return request.accept_languages.best_match(LANGUAGES.keys())
@application.route('/locale/<locale>/', methods=['GET'])
def set_locale(locale):
session['locale'] = locale
redirect_to = request.args.get('redirect_to', '/')
return redirect(redirect_to) # Change this to previous url
不幸的是,main.py
无法从应用程序工厂访问babel
变量.我应该如何解决这个问题?
Unfortunately, main.py
doesn't have access to the babel
variable from the application factory. How should I go about solving this?
推荐答案
在这种情况下,Flask扩展被设计为无需应用程序实例即可实例化.在工厂外,定义您的扩展.在工厂内部,调用init_app
将该应用程序与扩展名相关联.
Flask extensions are designed to be instantiated without an app instance for exactly this case. Outside the factory, define your extensions. Inside the factory, call init_app
to associate the app with the extension.
babel = Babel()
def create_app():
...
babel.init_app(app)
...
现在babel
名称可以随时导入,而不仅仅是在创建应用程序之后.
Now the babel
name is importable at any time, not just after the app has been created.
您似乎已经使用db
(Flask-SQLAlchemy)扩展名正确地执行了此操作.
You already appear to be doing this correctly with the db
(Flask-SQLAlchemy) extension.
在您的特定babel.localeselector
示例中,将其放在babel
旁边可能更有意义,因为它是在其中定义的.
In the case of your specific babel.localeselector
example, it might make more sense to put that next to babel
since it's being defined there.
这篇关于访问在应用程序工厂中定义的Flask扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!