【问题标题】:Flask Babel RuntimeError: Working outside of request contextFlask Babel RuntimeError:在请求上下文之外工作
【发布时间】:2021-06-18 18:37:21
【问题描述】:

我尝试在一个 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.

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

【问题讨论】:

    标签: python flask localization plotly-dash python-babel


    【解决方案1】:

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

    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 在应用上下文之外被初始化,但本地选择器在上下文中。对我来说这没有多大意义,因为 localeselector 仍然不在请求上下文中,但它正在工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多