Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is threading.local() a safe way to store variables for a single request in Google AppEngine?

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?

like image 610
Albert Avatar asked Sep 20 '14 13:09

Albert


1 Answers

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.

like image 185
Martijn Pieters Avatar answered Oct 04 '22 08:10

Martijn Pieters