与 aiohttp 网络服务器共享状态
Shared state with aiohttp web server
我的 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: 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'
我的 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: 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'