Search code examples
pythonpython-asynciofastapiuvloop

python Unable to get return values from async function using HTTP requests


I'm trying to rewrite my flask application to FastAPI which uses uvloop as the base. When I execute code without the routes, I see no issue and executes as expected. But throws me error after I add the routes and hit a request using Postman.

> INFO: ('172.17.0.1', 42352) - "GET /api/v1/getpass HTTP/1.1" 500
> ERROR: Exception in ASGI application Traceback (most recent call
> last):   File
> "/usr/local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py",
> line 375, in run_asgi
>     result = await app(self.scope, self.receive, self.send)   File "/usr/local/lib/python3.6/site-packages/starlette/applications.py",
> line 133, in __call__
>     await self.error_middleware(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/middleware/errors.py",
> line 177, in __call__
>     raise exc from None   File "/usr/local/lib/python3.6/site-packages/starlette/middleware/errors.py",
> line 155, in __call__
>     await self.app(scope, receive, _send)   File "/usr/local/lib/python3.6/site-packages/starlette/exceptions.py", line
> 73, in __call__
>     raise exc from None   File "/usr/local/lib/python3.6/site-packages/starlette/exceptions.py", line
> 62, in __call__
>     await self.app(scope, receive, sender)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 590, in __call__
>     await route(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 208, in __call__
>     await self.app(scope, receive, send)   File "/usr/local/lib/python3.6/site-packages/starlette/routing.py", line
> 41, in app
>     response = await func(request)   File "/usr/local/lib/python3.6/site-packages/fastapi/routing.py", line 111,
> in app
>     raw_response = await dependant.call(**values)   File "./iowait.py", line 51, in get_pvt
>     print(kpair) UnboundLocalError: local variable 'kpair' referenced before assignment

My Code:

import random
import asyncio as aio

from fastapi import FastAPI
from pydantic import BaseModel


get_id = '/api/v1/getid'
get_pass = '/api/v1/getpass'
app = FastAPI()
key_pass_list = [
    {
        'uid' : 'uid1',
        'pass' : 'pass1'
    },
    {
        'uid' : 'uid2',
        'pass' : 'pass2'
    },
    {
        'uid' : 'uid3',
        'pass' : 'pass3'
    },
]
id_list = [_['uid'] for _ in key_pass_list]


class KeyDoc(BaseModel):
    uid : str


async def key_pass(uid):
    for keypair in key_pass_list:
        if keypair['uid'] == uid:
            return keypair
    return {uid: 'Key not Found'}


@app.get(get_pass)
async def get_pvt(key_doc: KeyDoc):
    uid = key_doc.uid
    print('uid :' + uid)

    try:
        myloop = aio.get_event_loop()
        kpair = myloop.run_until_complete(aio.wait([key_pass(uid)]))
        await kpair
    except Exception as err:
        print(err)

    print(kpair)
    return None


@app.get(get_id)
async def get_pub():
    return random.choice(id_list)


@app.get("/")
async def root():
    return {"message": "Test-AIO"}

NOTE
get_id and / route works anytime because there is no logic, it fails with the get_pass requests.
Any help or pointers on this is very much appreciated.
Thank you


Solution

  • Two things here. Firstly, using aio.get_event_loop() is throwing an exception This event loop is already running before await kpair which throws the UnboundLocalError you're seeing when trying to print a non-existent variable. You can see this behavior by adding kpair = None under your first print statement in get_pvt. Below is how you would structure this using asyncio.wait.

    @app.get(get_pass)
    async def get_pvt(key_doc: KeyDoc):
        uid = key_doc.uid
        print('uid :' + uid)
        done = set()
        try:
            done, pending = await aio.wait([key_pass(uid)])
        except Exception as err:
            print(err)
    
        if done:
            for task in done:
                print(task.result())
        return None