我的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
?
答案 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'