Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to store per-request data on flask.request?

Tags:

python

flask

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?

like image 489
Panda Avatar asked Jun 15 '17 15:06

Panda


People also ask

Is Flask request thread safe?

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.

How many requests can Flask handle per second?

For reference, the Flask benchmarks on techempower give 25,000 requests per second.

Are global variables thread safe in Flask how do I share data between requests?

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.

Can Flask handle HTTP requests?

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.


1 Answers

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.

like image 186
davidism Avatar answered Sep 28 '22 09:09

davidism