2016-11-15 75 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

謝謝!我很難找到答案。 –