Can the flask.request
object be used similarly to flask.g
to store per-request data?
I am writing a library that is compatible with both Flask and Django. I plan to store information on the request object in both cases. Can I safely store objects on the request, say request.user
, with the assurance that it will not be shared between different requests?
Flask code has to be thread-safe, also called re-entrant. Local variables and parameters are always thread-safe. Instance variables, class variables, and global variables may not be thread-safe (but they might be). Nevertheless, threads and shared variables can be useful.
For reference, the Flask benchmarks on techempower give 25,000 requests per second.
You can't use global variables to hold this sort of data. Not only is it not thread safe, it's not process safe, and WSGI servers in production spawn multiple processes. Not only would your counts be wrong if you were using threads to handle requests, they would also vary depending on which process handled the request.
Flask has different decorators to handle http requests. Http protocol is the basis for data communication in the World Wide Web. Used to send HTML form data to the server. The data received by the POST method is not cached by the server.
Yes, it is safe. The request object is unique per request.
Typically g
is used because it is an empty namespace specifically created for holding data during a request.
request
is an internal object with existing meaning, although it is common for libraries to use it for storage, leaving g
for "application level" data.
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