Web.py Shared Variables
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. than
Solution 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 = {}
defload_cache():
"""Load hotels into {id: data} dict cache."""
rows = db.select('hotels')
for row in rows:
cache[row.id] = row
defget_hotel(hotel_id):
"""Get data for hotel with given ID, or return None if not found."""ifnot cache:
raise Exception('hotels cache not loaded')
return cache.get(hotel_id)
main.py:
import hotels
def main():
hotels.load_cache()
start_server()
Solution 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
Post a Comment for "Web.py Shared Variables"