FastAPI async endpoint not deleting temporary audio files after processing
22:58 29 Jun 2026

I have a FastAPI voice endpoint that saves an uploaded audio file to disk, processes it, and then tries to delete it in a finally block. But the files are not being deleted.

Here is my code:

@app.post("/voice")
async def voice(
    telegramId: str = Form(...),
    username: str = Form(""),
    firstName: str = Form(""),
    audio: UploadFile = File(...),
):
    user = get_or_create_user(telegramId, username, firstName)
    os.makedirs("uploads", exist_ok=True)
    path = os.path.join("uploads", f"{uuid4().hex}.oga")

    try:
        with open(path, "wb") as f:
            f.write(await audio.read())

        result = voice_to_text(path)

        if not native_text:
            return {"reply": "Could not understand audio", "buttons": []}

    finally:
        if os.path.exists(path):
            os.remove(path)
audio fastapi