与aiohttp Web服务器共享状态

时间:2016-11-15 17:31:21

标签: python python-3.x async-await python-asyncio aiohttp

我的aiohttp网络服务器使用随时间变化的全局变量:

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)

结果:

  

UnboundLocalError:在赋值之前引用的局部变量'shared_item'

如何正确使用共享变量shared_item

1 个答案:

答案 0 :(得分:6)

将您的共享变量推送到应用程序的上下文中:

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'