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

查看:60
本文介绍了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')        

推荐答案

只需在主(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.

检查有关Blueprint api的链接在Flask中.

Check this link about the api of Blueprint in Flask.

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

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