与aiohttp Web服务器的共享状态 [英] Shared state with aiohttp web server
本文介绍了与aiohttp Web服务器的共享状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 aiohttp
网络服务器使用随时间变化的全局变量:
My aiohttp
webserver uses a global variable that changes over time:
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'
UnboundLocalError: local variable 'shared_item' referenced before assignment
如何正确使用共享变量 shared_item
?
How would I properly use a shared variable shared_item
?
推荐答案
将共享变量推入应用程序的上下文中:
Push your shared variable into application's context:
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 Web服务器的共享状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文