added cache and FileResponse for range requests to seek meia
This commit is contained in:
32
app/api.py
32
app/api.py
@@ -18,6 +18,7 @@ api_key_header = APIKeyHeader(name="X-API-Key")
|
||||
FTP_URL = os.getenv("FTP_URL")
|
||||
FTP_LOGIN = os.getenv("FTP_LOGIN")
|
||||
FTP_PASSWORD = os.getenv("FTP_PASSWORD")
|
||||
CACHE_DIR = "cache"
|
||||
|
||||
def verify_api_key(api_key: str = Security(api_key_header)):
|
||||
if api_key != API_KEY:
|
||||
@@ -58,29 +59,38 @@ async def save_file(file: UploadFile = File(...), api_key: str = Depends(verify_
|
||||
|
||||
ftp.storbinary(f"STOR {FILES_DIR}/{file_url}", buffer)
|
||||
ftp.quit()
|
||||
|
||||
cached = os.path.join(CACHE_DIR, file_url)
|
||||
if os.path.exists(cached):
|
||||
os.remove(cached)
|
||||
|
||||
return {"status": "saved", "filename": file_url}
|
||||
except Exception as e:
|
||||
db.remove_file(file_url)
|
||||
|
||||
return {"status": "error", "message": f"Could not save file {file_url}: {e}"}
|
||||
else:
|
||||
return {"status": "file_exists", "filename": existed_url}
|
||||
|
||||
@app.get("/file/{filename}")
|
||||
async def get_file(filename: str, raw: bool = False, api_key: str = Depends(verify_api_key)):
|
||||
try:
|
||||
ftp = FTP(FTP_URL)
|
||||
ftp.login(FTP_LOGIN, FTP_PASSWORD)
|
||||
buffer = BytesIO()
|
||||
ftp.retrbinary(f"RETR {FILES_DIR}/{filename}", buffer.write)
|
||||
ftp.quit()
|
||||
buffer.seek(0)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {e}")
|
||||
local_path = os.path.join(CACHE_DIR, filename)
|
||||
|
||||
if not os.path.exists(local_path):
|
||||
try:
|
||||
ftp = FTP(FTP_URL)
|
||||
ftp.login(FTP_LOGIN, FTP_PASSWORD)
|
||||
with open(local_path, "wb") as f:
|
||||
ftp.retrbinary(f"RETR {FILES_DIR}/{filename}", f.write)
|
||||
ftp.quit()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {e}")
|
||||
|
||||
if raw:
|
||||
return PlainTextResponse(buffer.getvalue().decode("utf-8", errors="ignore"))
|
||||
with open(local_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
return PlainTextResponse(f.read())
|
||||
|
||||
return StreamingResponse(buffer, media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
||||
return FileResponse(local_path, filename=filename)
|
||||
|
||||
|
||||
from ftplib import FTP
|
||||
|
||||
Reference in New Issue
Block a user