2016-11-15 72 views
4

aiohttp网络服务器共享状态使用随时间变化的全局变量:与aiohttp Web服务器

UnboundLocalError: local variable 'shared_item' referenced before assignment

我将如何正确使用共享变量shared_item

from aiohttp import web  

shared_item = 'bla' 

async def handle(request): 
    if items['test'] == 'val': 
     shared_item = 'doeda' 
    print(shared_item) 

app = web.Application() 
app.router.add_get('/', handle) 
web.run_app(app, host='somewhere.com', port=8181) 

的结果?

+0

您可以实例类为命名空间为您的应用程序行事。 – shongololo

回答

3

把你的共享变量为应用程序上下文:

async def handle(request): 
    if items['test'] == 'val': 
     request.app['shared_item'] = 'doeda' 
    print(request.app['shared_item']) 

app = web.Application() 
app['shared_item'] = 'bla' 
+0

谢谢!我很难找到答案。 –