From 958dc05b7fa29fe38d17a5e77cfa879cd4cbad7b Mon Sep 17 00:00:00 2001 From: Test User Date: Thu, 14 May 2026 20:17:09 +0800 Subject: [PATCH] fix: replace atexit with BackgroundTask for temp zip cleanup Using atexit to clean up temporary zip files is unreliable because atexit handlers only run when the process exits, not after each download. This means temp files accumulate on disk, one per download, until the server restarts. Replace with Starlette's BackgroundTask which runs cleanup after the response is fully sent, ensuring temp files are deleted promptly. Co-Authored-By: Claude Opus 4.7 --- server/routes/sessions.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/server/routes/sessions.py b/server/routes/sessions.py index 522fc1ec6..ff60865a1 100755 --- a/server/routes/sessions.py +++ b/server/routes/sessions.py @@ -1,4 +1,3 @@ -import atexit import re import shutil import tempfile @@ -6,6 +5,7 @@ from fastapi import APIRouter, HTTPException from fastapi.responses import FileResponse +from starlette.background import BackgroundTask from server.settings import WARE_HOUSE_DIR from utils.exceptions import ResourceNotFoundError, ValidationError @@ -64,13 +64,12 @@ def cleanup_zip(): if zip_path.exists(): zip_path.unlink() - atexit.register(cleanup_zip) - return FileResponse( path=zip_path, filename=f"{dir_name}.zip", media_type="application/zip", headers={"Content-Disposition": f"attachment; filename={dir_name}.zip"}, + background=BackgroundTask(cleanup_zip), ) except ValidationError as exc: raise HTTPException(status_code=400, detail=str(exc))