【问题标题】:Application-wide request hooks in Flask. How to implement?Flask 中的应用程序范围的请求挂钩。如何实施?
【发布时间】:2018-01-04 06:11:22
【问题描述】:

在应用工厂内部定义共享请求钩子可以吗?

def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    db.init_app(app)
    csrf.init_app(app)
    login_manager.init_app(app)
    babel.init_app(app)

    @app.before_request
    def before_request_callback():
        if request.view_args and 'locale' in request.view_args:
            if request.view_args['locale'] not in app.config['SUPPORTED_LOCALES']:
                return abort(404)
            g.locale = request.view_args['locale']
            request.view_args.pop('locale')

    from . app_area__main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from . app_area__admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')        

【问题讨论】:

  • Blueprint 也有 before_app_request 装饰器。
  • @stamaimer 你的意思是我应该在我的蓝图中从一个单独的模块中引用它/有一个共享的函数来装饰?

标签: python flask architecture


【解决方案1】:

只需在您的 main(app_area_main) 蓝图中使用 before_app_request 注册一个函数。例如:

@main_blueprint.before_app_request
def before_app_request():
    pass

所有传递给应用的请求都会调用该函数。

查看link关于 Flask 中 Blueprint 的 api。

【讨论】:

  • 嗯,这样就足够了 - 只为 main_blueprint 注册(省略其他蓝图的注册)?文档中的 '即使在蓝图之外' 行是否暗示有一次性注册?
  • 是的,因为装饰器的名字是before_app_request而不是before_request
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多