web.py shared variables

家住魔仙堡 提交于 2019-12-10 16:12:51

问题


In web.py i need to create a shared variable, for which multiple threads(requests) can read or write to that variable.

What is the preferred way, for this kind of a situation.

thanks.


回答1:


I'm not sure this is really a web.py question, but we do this sort of thing all the time for process-wide caches (that is, dict caches that are shared by all request threads). We use web.py, but my example below should apply to any multi-threaded Python web server.

hotels.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)

main.py:

import hotels

def main():
    hotels.load_cache()
    start_server()



回答2:


I find lots of code using this container: web.ctx

like

web.ctx.orm = scoped_session(sessionmaker(bind=engine))
web.ctx.session = web.config._session

u can init those in a function, then process them:

app.add_processor(web.loadhook(init_func))

Not sure it works or not for your scenario



来源:https://stackoverflow.com/questions/5677561/web-py-shared-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!