dinhanhx / dinhanhx/fastapi-docx

🐛 Bug: cleanup() in finally blocks creates BackgroundTask but never executes it

Open
#1 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
0
Forks
0
PR merge metrics
No merged PRs in 30d

Description

## Description

In `main.py`, every endpoint calls `cleanup(input_path)` inside a `finally` block. However, `cleanup()` (defined in `utils.py:64`) returns a `BackgroundTask` object — it does **not** delete the file immediately. Since the returned `BackgroundTask` is never attached to a response or awaited, the input file is **never cleaned up**.

## Files & Lines

- `fastapi-docx/main.py` lines 54, 82, 110, 138 — `cleanup(input_path)` in `finally` blocks
- `fastapi-docx/utils.py` lines 64-75 — `cleanup()` returns a `BackgroundTask`, doesn't delete directly

## Why It Matters

Uploaded temp files accumulate on disk indefinitely, eventually filling up storage. Only the output file gets cleaned (via `background=cleanup(output_path)` in `FileResponse`), but input files are leaked.

## Suggested Fix

Either:
1. Call the internal `_delete()` directly for the input path cleanup:
```python
# In utils.py, add:
def cleanup_now(*paths: Path) -> None:
for p in paths:
try:
Path(p).unlink(missing_ok=True)
except Exception:
pass

# In main.py finally blocks:
cleanup_now(input_path)
```

2. Or combine both cleanups into the `FileResponse` background task:
```python
return FileResponse(
path=output_path,
...,
background=cleanup(input_path, output_path), # clean both
)
# And remove the finally block
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.