在 web.py 我需要创建一个共享变量,多个线程(请求)可以读取或写入该变量。
对于这种情况,首选方式是什么。
谢谢。
我不确定这真的是一个 web.py 问题,但我们一直在为进程范围的缓存(即所有请求线程共享的 dict 缓存)做这种事情。我们使用 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()
我发现很多使用这个容器的代码:web.ctx
像
web.ctx.orm = scoped_session(sessionmaker(bind=engine))
web.ctx.session = web.config._session
你可以在一个函数中初始化它们,然后处理它们:
app.add_processor(web.loadhook(init_func))
不确定它是否适用于您的场景