Flask 中的应用程序范围的请求钩子.如何实施? [英] Application-wide request hooks in Flask. How to implement?

查看:24
本文介绍了Flask 中的应用程序范围的请求钩子.如何实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it ok to define a shared request hook inside the application factory?

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')        

推荐答案

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

Just register a function with before_app_request in your main(app_area_main) blueprint. For example:

@main_blueprint.before_app_request
def before_app_request():
    pass

传递给应用的所有请求都将调用该函数.

All request pass to the app will invoke that function.

检查这个link关于蓝图的api在烧瓶中.

Check this link about the api of Blueprint in Flask.

这篇关于Flask 中的应用程序范围的请求钩子.如何实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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