问题
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