python flask request hook python flask request hook flask flask

python flask request hook


You may be looking for flask.Flask.before_request.

Also you won't necessarily be able to add data into the request attributes form and args as they are immutable, consider using g which is a thread local.

Example usage:

from flask import Flask, request, gapp = Flask(__name__)@app.route('/')def home():    return g.target + '\n'@app.before_requestdef before_req():    g.target = request.args.get('target', 'default')if __name__ == '__main__':    app.run()

Usage:

$ wget -qO - 'http://localhost:5000/?target=value'value$ wget -qO - 'http://localhost:5000/?key=value'default


A common pattern to share data between request hook functions and view functions isto use the g context global. For example, a before_request handler can load the loggedin user from the database and store it in g.user. Later, when the view function is invoked,it can access the user from there. Or the logged in new user may be require to perform some activities before he can access a page in a web application. For example, The new user may be require to verify his/her email before access the home page of the web application. The before_request decorator will intercept the particular view function which is the home page he intend to access and and prevent him from access it untill the email is verified.

Click there to learn more about how how before_request and after_request works in flask. I hope you find it helpful.