According to the answer given in Is it safe to store per-request data on flask.request? it seems that the g
object is request-local (= has the lifetime of a single request). Maybe I misunderstood this answer, but the Flask documentation states that the g
object would be global which seems to contradict this answer.
The documentation itself is a bit short about these details, so please would you mind to explain the details to the contexts and the global object g
? Specifically to address the following questions:
request
object, the g
object or which kind of object?)app
object, the g
object or which kind of object?)app
or g
objects then need to be initialized individually for the lifetime of each worker process.)In order to store data across multiple requests, Flask utilizes cryptographically-signed cookies (stored on the web browser) to store the data for a session. This cookie is sent with each request to the Flask app on the server-side where it's decoded.
The naming scheme is Flask-ExtensionName or ExtensionName-Flask. It must provide exactly one package or module named flask_extension_name . The extension must be BSD or MIT licensed. It must be open source and publicly available.
In order to store data for the lifetime of a single request, how should that be done?
The g
object is designed for this. The documentation states:
Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.
Although the documentation refers to g
as "global", that's not really accurate - "thread-global" would be better.
In order to store data for the lifetime of an application, how should that be done?
I think the answer to this question answers this as well (or better) than I could: Preserving global state in a flask application
Flask could be used in a multi-process environment. Is it correct to assume that in such a mode of operation there will be multiple application-wide objects? (This would imply that all of these app or g objects then need to be initialized individually for the lifetime of each worker process.)
In a multi-process environment, each request is handled as a seperate thread, and g
is intialized and destroyed on a per-request basis, so there will be as many concurrent g
object as threads - though each thread can only see it's own. In most scenarios I suspect there should only ever one app
object, an instance of the Flask() class created by the programmer, i.e. app = Flask(__name__)
or similar.
Blueprints and Application Dispatching are two way of having "multiple" application objects, in as far as you have multiple applications running concurrently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With