Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda