lexeme
lexeme

Reputation: 2973

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

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

Upvotes: 2

Views: 1590

Answers (1)

stamaimer
stamaimer

Reputation: 6475

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.

Upvotes: 5

Related Questions