I have a google appengine app where I want to set a global variable for that request only. Can I do this?
In request_vars.py
# request_vars.py
global_vars = threading.local()
In another.py
# another.py
from request_vars import global_vars
get_time():
return global_vars.time_start
In main.py
# main.py
import another
from request_vars import global_vars
global_vars.time_start = datetime.datetime.now()
time_start = another.get_time()
Questions: Considering multithreading, concurrent requests, building on Google AppEngine, and hundreds (even thousands) of requests per second, will the value of time_start
always be equal to the value set in global_vars.time_start
in main.py
per request? Is this safe to use with multithreading/threadsafe enabled?
Yes, using threading.local
is an excellent method to set a per-request global. Your request will always be handled by one thread, on one instance in the Google cloud. That thread local value will be unique to that thread.
Take into account that the thread can be reused for future requests, and always reset the value at the start of the request.
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