refactor: 统一临时文件清理逻辑

This commit is contained in:
2026-06-01 18:29:24 +08:00
parent c061b66169
commit 118c5b1ab7
4 changed files with 21 additions and 20 deletions
+3 -8
View File
@@ -1,5 +1,4 @@
import re
from contextlib import suppress
from datetime import datetime
from pathlib import Path
from typing import Optional
@@ -12,17 +11,13 @@ from starlette.background import BackgroundTask
from app import state
from app.config import CACHE_DIR
from app.database import DatabaseManager
from app.utils.files import remove_file_safely
router = APIRouter(tags=["database"])
INVALID_SHEET_NAME_CHARS = re.compile(r"[:\\/?*\[\]]")
def _remove_file(path: Path) -> None:
with suppress(OSError):
path.unlink()
def _resolve_requested_tables(
table_name: Optional[str],
table_names: Optional[list[str]],
@@ -227,12 +222,12 @@ async def download_table(
df.to_excel(writer, sheet_name=_make_sheet_name(name, used_sheet_names), index=False)
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
except Exception:
_remove_file(filepath)
remove_file_safely(filepath)
raise
return FileResponse(
path=str(filepath),
filename=filename,
media_type=media_type,
background=BackgroundTask(_remove_file, filepath),
background=BackgroundTask(remove_file_safely, filepath),
)
+5 -11
View File
@@ -1,5 +1,4 @@
import zipfile
from contextlib import suppress
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -10,17 +9,12 @@ from starlette.background import BackgroundTask
from app import state
from app.config import CACHE_DIR
from app.utils.files import format_size, get_dir_size
from app.utils.files import format_size, get_dir_size, remove_file_safely
router = APIRouter(tags=["history"])
def _remove_file(path: Path) -> None:
with suppress(OSError):
path.unlink()
def _safe_filename_part(value: str) -> str:
safe = "".join(char if char.isalnum() or char in {"-", "_"} else "_" for char in value)
return safe.strip("_") or "history"
@@ -202,14 +196,14 @@ async def download_history(record_id: str = Body(..., embed=True)):
try:
_zip_directory(work_dir, archive_path)
except Exception:
_remove_file(archive_path)
remove_file_safely(archive_path)
raise
return FileResponse(
path=str(archive_path),
filename=filename,
media_type="application/zip",
background=BackgroundTask(_remove_file, archive_path),
background=BackgroundTask(remove_file_safely, archive_path),
)
@@ -238,12 +232,12 @@ async def download_history_file(
try:
_zip_history_item(target_path, archive_path)
except Exception:
_remove_file(archive_path)
remove_file_safely(archive_path)
raise
return FileResponse(
path=str(archive_path),
filename=filename,
media_type="application/zip",
background=BackgroundTask(_remove_file, archive_path),
background=BackgroundTask(remove_file_safely, archive_path),
)
+7 -1
View File
@@ -1,6 +1,13 @@
from pathlib import Path
def remove_file_safely(path: Path) -> None:
try:
path.unlink()
except OSError:
pass
def get_dir_size(path: Path) -> int:
total_size = 0
try:
@@ -26,4 +33,3 @@ def format_size(size_bytes: int) -> str:
return f"{value:.2f} {unit}"
value /= 1024.0
return f"{value:.2f} PB"