【问题标题】:Shared state with aiohttp web server与 aiohttp 网络服务器共享状态
【发布时间】:2017-03-29 16:59:07
【问题描述】:

我的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

【问题讨论】:

  • 您可以将类实例化为您的应用程序的命名空间。

标签: python python-3.x async-await python-asyncio aiohttp


【解决方案1】:

将您的共享变量推送到应用程序的上下文中:

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'

【讨论】:

  • 谢谢!我很难找到答案。
  • 从 3.5.4 版开始,这已被弃用 (DeprecationWarning: Changing state of started or joined application is deprecated)。现在推荐的方法是什么?
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 2016-02-24
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多