Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
Use FastAPI to interact with async loop

I am running coroutines of 'workers' whose job it is to wait 5s, get values from an asyncio.Queue() and print them out continually.

q = asyncio.Queue()

def worker():
    while True:
        await asyncio.sleep(5)
        i = await q.get()
        print(i)
        q.task_done()

async def main(q):
    workers = [asyncio.create_task(worker()) for n in range(10)]
    await asyncio.gather(*workers)


if __name__ == "__main__":
    asyncio.run(main())

I would like to be able to interact with the queue through http requests using FastAPI. For example POST requests that would 'put' items in the queue for the workers to print.

I'm unsure how I can run the coroutines of the workers concurrently with FastAPI to achieve this effect. Uvicorn has its own event loop I believe and my attempts to use asyncio methods have been unsuccessful.

The router would look something like this I think.

@app.post("/")
async def put_queue(data:str):
    return q.put(data)

And I'm hoping there's something that would have an effect like this:

await asyncio.gather(main(),{FastApi() app run})
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

One option would be to add a task that wraps your main coroutine in a on startup event

import asyncio
@app.on_event("startup")
async def startup_event():
    asyncio.create_task(main())

This would schedule your main coroutine before the app has been fully started.

Important here is that you don't await the created task as it would basically block startup_event forever

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda