微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flask Babel RuntimeError:在请求上下文之外工作

如何解决Flask Babel RuntimeError:在请求上下文之外工作

我尝试在 Flask 应用程序中设置多个 Dash 应用程序并使用 Flask Babel。

from flask import Flask,request
from flask_babel import Babel,gettext
from werkzeug.middleware.dispatcher import dispatcherMiddleware

def init_app():
    """Construct core Flask application."""
    app = Flask(__name__,instance_relative_config=False)
    app.config.from_object("config.Config")

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(app.config["LANGUAGES"])

    with app.app_context():
        # Import parts of our core Flask app
        from . import routes
        from .plotly.sec import init_dashboard_sec
        from .plotly.bafin import init_dashboard_bafin

        # app = init_dashboard(app)
        app = dispatcherMiddleware(app,{
            "/s": init_dashboard_sec(app),"/b": init_dashboard_bafin(app)
        })

        return app

但是,由于我添加了 babel 装饰函数,因此出现以下错误

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

我试图将函数移动到不同的位置,但错误保持不变。

解决方法

我不知道这是否是正确的解决方案,但以下方法有效:

from flask import Flask,request
from flask_babel import Babel,gettext
from werkzeug.middleware.dispatcher import DispatcherMiddleware

def init_app():
    """Construct core Flask application."""
    app = Flask(__name__,instance_relative_config=False)
    app.config.from_object("config.Config")
    babel = Babel(app)

    with app.app_context():
        # Import parts of our core Flask app
        from . import routes
        from .plotly.sec import init_dashboard_sec
        from .plotly.bafin import init_dashboard_bafin

        # app = init_dashboard(app)
        app = DispatcherMiddleware(app,{
            "/s": init_dashboard_sec(app),"/b": init_dashboard_bafin(app)
        })

        @babel.localeselector
        def get_locale():
            return request.accept_languages.best_match(["de","en"])

        return app

所以 babel 在应用上下文之外初始化,但 localselector 在上下文内。对我来说这没有多大意义,因为 localeselector 仍然在请求上下文之外,但它正在工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。