Common variables web.py

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

What is the preferred method for this kind of situation.

thanks.

+4
source share
2 answers

I'm not sure that this is really a web.py question, but we do all the time for the caches of all processes (i.e. cache files shared by all request flows). 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
source

I find a lot of code using this container: web.ctx

like

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

u can initialize functions in functions and then process them:

 app.add_processor(web.loadhook(init_func)) 

Not sure if it works or not for your scenario

+1
source

All Articles