Spaces:
Sleeping
Sleeping
File size: 1,444 Bytes
02e5116 bba27fd 02e5116 bba27fd 02e5116 bba27fd 02e5116 bba27fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
from fastapi import FastAPI, UploadFile, File, BackgroundTasks
from fastapi.responses import HTMLResponse, FileResponse
import shutil
import os
import uuid
from pathlib import Path
import time
app = FastAPI()
TEMP_DIR = Path("/tmp/uploads")
TEMP_DIR.mkdir(parents=True, exist_ok=True)
# Background cleanup: delete files older than 1 hour
def cleanup_old_files():
now = time.time()
for f in TEMP_DIR.iterdir():
if now - f.stat().st_mtime > 3600:
try:
f.unlink()
except Exception:
pass
@app.get("/", response_class=HTMLResponse)
async def main():
html_path = Path(__file__).parent / "static" / "index.html"
return HTMLResponse(content=html_path.read_text(), status_code=200)
@app.post("/upload")
async def upload_temp_file(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
):
# Schedule cleanup task
background_tasks.add_task(cleanup_old_files)
unique_name = f"{uuid.uuid4()}_{file.filename}"
dest_path = TEMP_DIR / unique_name
with dest_path.open("wb") as buf:
shutil.copyfileobj(file.file, buf)
return {"filename": unique_name, "url": f"/files/{unique_name}"}
@app.get("/files/{filename}")
async def serve_file(filename: str):
file_path = TEMP_DIR / filename
if not file_path.exists():
return {"error": "File not found"}
return FileResponse(path=str(file_path), filename=filename) |