Globals
As discussed earlier in this chapter, Flask provides a mechanism to store global variables that are unique to a particular thread and request context. That's used for request and session, but is also available to store any custom object.
The flask.g variable contains all globals, and you can set whatever attributes you want on it.
In Flask, the @app.before_request decorator can be used to point a function that the app will call every time a request is made just before it dispatches the request to a view.
It's a typical pattern in Flask to use before_request to set values in the globals. That way, all the functions that are called within the request context can interact with g and get the data.
In the following example, we copy the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access