本文介绍了threading.local()是一种安全的方式,可以在Google AppEngine中存储单个请求的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个谷歌appengine应用程序,我只想为该请求设置一个全局变量。我可以这样做吗?

I have a google appengine app where I want to set a global variable for that request only. Can I do this?

在request_vars.py中

In request_vars.py

# request_vars.py

global_vars = threading.local()

在another.py

In another.py

# another.py

from request_vars import global_vars
get_time():
    return global_vars.time_start

在main.py中

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()

问题:考虑到多线程,基于Google AppEngine构建的并发请求以及每秒数百(甚至数千)个请求, time_start 的值始终等于 global_vars.time_start main.py 每个请求中?这是安全的使用多线程/线程安全启用?

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?

推荐答案

是的,使用 threading.local 是设置每个请求全局的极好方法。您的请求将始终由一个线程处理,即Google云中的一个实例。该线程本地值对该线程是唯一的。

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.

这篇关于threading.local()是一种安全的方式,可以在Google AppEngine中存储单个请求的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:10