Asyncio With Uvicorn ASGI Server

Viewed 17

I have a simple program that I am trying to write. The goal is to have a process that calculates some data and pushes it to the queue. When a request arrives the element in the queue is picked up and sent back to the user. Not sure what I am doing wrong. Thank you.

import asyncio
from uvicorn import Config, Server
import random

queue= asyncio.Queue(1)

async def add(queue):
  while True:
    await queue.put(str(random.randint(1, 10000)))
    print(queue.qsize())
    await asyncio.sleep(1)


async def app(scope, receive, send):
    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [
            [b'content-type', b'text/plain'],
        ]
    })
    val = await queue.get()
    queue.task_done()
    await send({
        'type': 'http.response.body',
        'body': bytes(val, 'utf-8'),
    })


loop = asyncio.new_event_loop()
config = Config(app=app, loop=loop)
loop.create_task(add(queue))
server = Server(config)
loop.run_until_complete(server.serve())

The code basically starts a uvicorn server python example.py I am creating a new loop and starting the task. All works fine as long as the number of elements in the queue is greater than zero. When I call the endpoint and the number of elements in the queue are zero it throws the following error.

Task exception was never retrieved
future: <Task finished name='Task-1' coro=<add() done, defined at uvicron_asgi_server/simple.py:7> exception=RuntimeError("Task <Task pending name='Task-1' coro=<add() running at uvicron_asgi_server/simple.py:9>> got Future <Future pending> attached to a different loop")>
Traceback (most recent call last):
  File "uvicron_asgi_server/simple.py", line 9, in add
    await queue.put(str(random.randint(1, 10000)))
  File "/usr/local/lib/python3.9/asyncio/queues.py", line 128, in put
    await putter
RuntimeError: Task <Task pending name='Task-1' coro=<add() running at uvicron_asgi_server/simple.py:9>> got Future <Future pending> attached to a different loop

0 Answers
Related