Spaces:
Running
Running
Commit ·
2fc7c46
1
Parent(s): 667075f
fix: make /api/pdf serve from SFTP with timeout
Browse files- backend/api.py +21 -8
backend/api.py
CHANGED
|
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import os
|
|
|
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
from typing import Any, Dict
|
| 7 |
|
|
@@ -104,14 +106,25 @@ def root() -> Dict[str, str]:
|
|
| 104 |
|
| 105 |
@app.get("/api/pdf/{pdf_id}")
|
| 106 |
def get_pdf(pdf_id: str):
|
| 107 |
-
# Read
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
# Stream bytes back to UI
|
| 117 |
resp = PlainTextResponse(content=data)
|
|
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
+
import concurrent.futures
|
| 6 |
+
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any, Dict
|
| 9 |
|
|
|
|
| 106 |
|
| 107 |
@app.get("/api/pdf/{pdf_id}")
|
| 108 |
def get_pdf(pdf_id: str):
|
| 109 |
+
# Read from SFTP path: /inserio/pdfs/<pdf_id>.pdf (SFTP_ROOT handles /inserio)
|
| 110 |
+
name = pdf_id
|
| 111 |
+
if not name.lower().endswith(".pdf"):
|
| 112 |
+
remote_path = f"pdfs/{name}.pdf"
|
| 113 |
+
else:
|
| 114 |
+
remote_path = f"pdfs/{name}"
|
| 115 |
+
|
| 116 |
+
# Hard timeout so requests never hang
|
| 117 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
|
| 118 |
+
fut = ex.submit(download_bytes, remote_path)
|
| 119 |
+
try:
|
| 120 |
+
data = fut.result(timeout=10)
|
| 121 |
+
except concurrent.futures.TimeoutError:
|
| 122 |
+
from fastapi import HTTPException
|
| 123 |
+
raise HTTPException(status_code=504, detail="SFTP timeout reading PDF")
|
| 124 |
+
|
| 125 |
+
# Return raw bytes
|
| 126 |
+
from fastapi.responses import Response
|
| 127 |
+
return Response(content=data, media_type="application/pdf")
|
| 128 |
|
| 129 |
# Stream bytes back to UI
|
| 130 |
resp = PlainTextResponse(content=data)
|