Flask Babel RuntimeError: Working outside of request context

Flask Babel RuntimeError: Working outside of request context

我尝试在一个 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 在上下文中。对我来说,这没有多大意义,因为语言环境选择器仍然在请求上下文之外,但它正在工作。

如果您可能正在对终端进行测试并收到错误,请执行此操作

from your_app import create_app
app = create_app()
with app.test_request_context(
        '/make_report/2017', data={'format': 'short'}):
    ##do something here

有关更多信息,您可以访问文档的这一部分以了解更多信息https://flask.palletsprojects.com/en/2.1.x/reqcontext/