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

不想你离开。 提交于 2019-12-30 03:13:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25949059/is-threading-local-a-safe-way-to-store-variables-for-a-single-request-in-googl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!