python - 与 aiohttp 网络服务器共享状态

标签 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: 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'

关于python - 与 aiohttp 网络服务器共享状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616145/

相关文章:

python - 查找列表中的哪个数字总和为某个数字但带有负数和小数

python - 如何更改数组中元素的索引

reactjs - 如何将 async/await 与 useEffect React hook 一起使用,我尝试了很多示例,但没有任何效果

python3 只有一个目录被导入到命名空间包中

python - 除了 : and except Exception as e: 之间的区别

c# - 如何从 ViewModel 异步更新 UI 元素

c# - MVC 4 中的异步操作过滤器

python - 将 RGB 颜色的 pandas 数据帧转换为十六进制

python - 从网站上显示的图表中获取数据

python - if 和 for 两边的括号