在 web.py 中我需要创建一个共享变量,为此多个 线程(请求)可以读取或写入该变量。
对于这种情况,首选方法是什么。
谢谢。
最佳答案
我不确定这是否真的是一个 web.py 问题,但我们一直在为进程范围的缓存(即所有请求线程共享的字典缓存)做这种事情。我们使用 web.py,但我下面的示例应该适用于任何多线程 Python Web 服务器。
酒店.py:
cache = {}
def load_cache():
"""Load hotels into {id: data} dict cache."""
rows = db.select('hotels')
for row in rows:
cache[row.id] = row
def get_hotel(hotel_id):
"""Get data for hotel with given ID, or return None if not found."""
if not cache:
raise Exception('hotels cache not loaded')
return cache.get(hotel_id)
主要.py:
import hotels
def main():
hotels.load_cache()
start_server()
关于python - web.py 共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677561/