访问在应用工厂中定义的 Flask 扩展 [英] Access a Flask extension that is defined in the app factory

查看:18
本文介绍了访问在应用工厂中定义的 Flask 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用应用工厂模式来设置我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆