我的aiohttp webserver使用随时间变化的全局变量:
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: local variable ‘shared_item’ referenced before assignment
我如何正确使用共享变量shared_item?
解决方法:
将共享变量推送到应用程序的上下文中:
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'