Application-wide request hooks in Flask. How to implement?

萝らか妹 提交于 2019-12-31 05:36:09

问题


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

回答1:


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.

Check this link about the api of Blueprint in Flask.



来源:https://stackoverflow.com/questions/45368995/application-wide-request-hooks-in-flask-how-to-implement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!