Request setup, teardown, and application globals
In some cases, a request-specific variable is needed across all view functions and needs to be accessed from the template as well. To achieve this, we can use Flask's decorator function @app.before_request
and the object g
. The function @app.before_request
is executed every time before a new request is made. The Flask object g
is a thread-safe store of any data that needs to be kept for each specific request. At the end of the request, the object is destroyed, and a new object is spawned at the start of a new request. For example, the following code checks whether the Flask session
variable contains an entry for a logged in user; if it exists, it adds the User
object to g
:
from flask import g, session, abort, render_template @app.before_request def before_request(): if ‘user_id’ in session: g.user = User.query.get(session[‘user_id’]) @app.route(‘/restricted’) def admin(): if g.user is None: abort(403) return render_template...