Spaces:
Sleeping
Sleeping
fix download race: use tempfile + BackgroundTasks, tránh Response content shorter than Content-Length
Browse files
backend/app/api/listing.py
CHANGED
|
@@ -2,7 +2,7 @@ import json
|
|
| 2 |
import os
|
| 3 |
import shutil
|
| 4 |
import uuid
|
| 5 |
-
from fastapi import APIRouter, File, UploadFile, Form, HTTPException
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
|
| 8 |
from ..config import settings
|
|
@@ -414,11 +414,15 @@ def serve_file(sid: str, filename: str):
|
|
| 414 |
|
| 415 |
|
| 416 |
@router.get("/download/{sid}")
|
| 417 |
-
def download_all(sid: str):
|
|
|
|
|
|
|
|
|
|
| 418 |
s = _get(sid)
|
| 419 |
-
|
|
|
|
|
|
|
| 420 |
|
| 421 |
-
import zipfile
|
| 422 |
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 423 |
for r in s.get("results") or []:
|
| 424 |
for img in r.get("images") or []:
|
|
@@ -432,6 +436,7 @@ def download_all(sid: str):
|
|
| 432 |
if os.path.exists(text_file):
|
| 433 |
zf.write(text_file, f"listing_text_{sid}.txt")
|
| 434 |
|
|
|
|
| 435 |
return FileResponse(zip_path, filename=f"listing_images_{sid}.zip", media_type="application/zip")
|
| 436 |
|
| 437 |
|
|
|
|
| 2 |
import os
|
| 3 |
import shutil
|
| 4 |
import uuid
|
| 5 |
+
from fastapi import APIRouter, File, UploadFile, Form, HTTPException, BackgroundTasks
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
|
| 8 |
from ..config import settings
|
|
|
|
| 414 |
|
| 415 |
|
| 416 |
@router.get("/download/{sid}")
|
| 417 |
+
def download_all(sid: str, background_tasks: BackgroundTasks):
|
| 418 |
+
import tempfile
|
| 419 |
+
import zipfile
|
| 420 |
+
|
| 421 |
s = _get(sid)
|
| 422 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
| 423 |
+
zip_path = tmp.name
|
| 424 |
+
tmp.close()
|
| 425 |
|
|
|
|
| 426 |
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 427 |
for r in s.get("results") or []:
|
| 428 |
for img in r.get("images") or []:
|
|
|
|
| 436 |
if os.path.exists(text_file):
|
| 437 |
zf.write(text_file, f"listing_text_{sid}.txt")
|
| 438 |
|
| 439 |
+
background_tasks.add_task(os.unlink, zip_path)
|
| 440 |
return FileResponse(zip_path, filename=f"listing_images_{sid}.zip", media_type="application/zip")
|
| 441 |
|
| 442 |
|