python - web.py 共享变量

标签 python web.py

在 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/

相关文章:

python - 为什么在无服务器 python 应用程序中使用 zappa/chalice?

python - 使用 Python Requests 和 BeautifulSoup 登录 Facebook

python - 让 str.count() 在 python 上工作

python - 在数据框中的列中的特定位置添加字符串

python - web.py:如何为任何 HTTP 方法选择性地隐藏带有 404 的资源?

python - webpy 中的 session - 获取所有类中的用户名

python - 无法在 OS X 上使用 python 2.6 让 web.py session 正常工作

python - 如何在 numpy/scipy 中实现像素数学

Python:python3 上 web.py 的替代方案