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

217
Visualizações
Fastapi async coroutines not removed when finished

With the code below, FINISHED coroutines seem never to be removed from the async loop. After every request from a client, an additional coroutine is added to the loop. What is the best way to remove finished coroutines and therefore not running into out of memory problems?

import uvicorn
import asyncio
from loguru import logger

app = FastAPI()
terminate = False

@app.get("/")
async def root():
    return {"message": "Hello World"}

async def print_coroutines():
    global terminate
    while not terminate:
        coroutines = asyncio.Task.all_tasks()
        logger.debug('Total number of coroutines: ' + str(len(coroutines)))
        for coro in coroutines:
            logger.debug(coro)
        await asyncio.sleep(2)

@app.on_event("startup")
async def startup_event():
    asyncio.get_event_loop().create_task(print_coroutines())

@app.on_event("shutdown")
async def shutdown_event():
    global terminate
    terminate = True

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=5000)

Console output after opening one browser window:    
  Total number of coroutines: 5
  <Task pending coro=<Server.startup.<locals>.handler() running
  <Task pending coro=<Server.serve() running 
  <Task finished coro=<Server.startup.<locals>.handler() done 
  <Task pending coro=<LifespanOn.main() running
  <Task pending coro=<print_coroutines() running
over 4 years ago · Santiago Trujillo
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