10

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?

Albert
  • 3,611
  • 3
  • 28
  • 52
  • In addition to the answer below, when using appengine you can use the environment for local storage, it's contents only exist for the current request. This does not necessarily hold true for non appengine environments. – Tim Hoffman Sep 21 '14 at 10:59

1 Answers1

11

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343