Shared state with aiohttp web server

匆匆过客 提交于 2019-12-10 09:22:45

问题


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)

Results in:

UnboundLocalError: local variable 'shared_item' referenced before assignment

How would I properly use a shared variable shared_item?


回答1:


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'


来源:https://stackoverflow.com/questions/40616145/shared-state-with-aiohttp-web-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!