Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared state with aiohttp web server

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?

like image 227
Berco Beute Avatar asked Nov 15 '16 17:11

Berco Beute


People also ask

Is Aiohttp safe?

Is aiohttp safe to use? The python package aiohttp was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.

Is Aiohttp asgi?

Almost all of the frameworks are ASGI-compatible (aiohttp and tornado are exceptions on the moment).


1 Answers

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'
like image 78
Andrew Svetlov Avatar answered Oct 21 '22 01:10

Andrew Svetlov