是否可以設置一個線程或類似的東西來在每個服務器請求之間存儲值?在整個服務器請求中設置並獲取線程或全局值
我知道線程或全局變量的值只在每個服務器請求期間獲取/設置,而且這些值不能在上下文之外更改,因爲所有內容都是在「映射」類中完成的。
儘管我只是很好奇這一點,因爲設置一個值並在每個請求上操作它會很好,但我不知道它可能是一個存儲在內存中的變量,以便稍後可以引用它。
我這樣說是因爲與Web應用程序相關的會話,cookie和everthing只能通過每個GET/POST請求來操縱。 Ø到目前爲止,這是我所:
import web
import threading
threadlocal = threading.local()
def set_value():
setattr(threadlocal, 'mythread', 'threadvalue')
def get_value():
return getattr(threadlocal, 'mythread', None)
urls = (
"/set_thread_value", "set_thread_value",
"/get_thread_value", "get_thread_value"
)
app = web.application(urls, globals())
t_globals = {
'template_thread': get_value()
}
render = web.template.render('templates', globals=t_globals)
class set_thread_value:
def GET(self):
set_value()
return get_value()
class get_thread_value:
def GET(self):
return get_value()
正如你可以看到,當你調用「set_thread_value」你設置線程值,並將其顯示在屏幕上,但當你叫「get_thread_value」你會得到無來代替。
您可能還注意到我想將線程傳遞給模板,以便可以使用其更新的值顯示它。
編輯:我不想使用mysql,mongodb或任何其他存儲系統來設置線程的值。
在此先感謝。
你知道應用程序通常是託管在多線程?你想要做的是明顯錯誤的。你的用例是什麼? –
我想設置該值,以便它可以顯示在模板上,我發現了一些我想要做的事情:http://stackoverflow.com/a/6688459/1747721 – Uuid
使用memcache或類似的東西 - 這就是它在 –