dinhanhx / dinhanhx/fastapi-docx

🐛 Bug: cleanup() in finally block creates BackgroundTask but never executes it — temp files leak

Open
#4 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`, the `cleanup(input_path)` call inside the `finally` block does **not** actually delete the file. It creates a `BackgroundTask` object that is immediately discarded.

## File & Line

`fastapi-docx/main.py`, lines 52, 55 (and same pattern in all other endpoints):

```python
finally:
cleanup(input_path) # ← Returns a BackgroundTask, doesn't execute!

return FileResponse(
path=output_path,
...
background=cleanup(output_path), # ← This one works because FileResponse runs it
)
```

## Why It Matters

Every uploaded file stays on disk forever in the temp directory (`TEMP_DIR`). Over time this fills up disk space. Only `output_path` gets cleaned (via FileResponse background task), but `input_path` never does.

## Suggested Fix

Either call the task directly:
```python
finally:
Path(input_path).unlink(missing_ok=True)
```

Or combine both paths into one background task:
```python
return FileResponse(
path=output_path,
...
background=cleanup(input_path, output_path),
)
```
and remove the `finally` block (but handle the error case separately to clean up input on failure).

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.