Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile
|
| 2 |
-
from fastapi.responses import FileResponse
|
|
|
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
-
#
|
| 10 |
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
|
@@ -16,12 +17,20 @@ allow_methods=["*"],
|
|
| 16 |
allow_headers=["*"],
|
| 17 |
)
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
UPLOAD_DIR = "uploads"
|
| 20 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
@app.post("/upload")
|
| 27 |
async def upload(file: UploadFile):
|
|
@@ -36,6 +45,8 @@ with open(file_path, "wb") as f:
|
|
| 36 |
return {"link": f"/file/{file_id}_{filename}"}
|
| 37 |
```
|
| 38 |
|
|
|
|
|
|
|
| 39 |
@app.get("/file/{filename}")
|
| 40 |
def get_file(filename: str):
|
| 41 |
file_path = f"{UPLOAD_DIR}/{filename}"
|
|
@@ -47,7 +58,7 @@ if not os.path.exists(file_path):
|
|
| 47 |
return FileResponse(file_path)
|
| 48 |
```
|
| 49 |
|
| 50 |
-
# Run
|
| 51 |
|
| 52 |
if **name** == "**main**":
|
| 53 |
import uvicorn
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, Request
|
| 2 |
+
from fastapi.responses import FileResponse, HTMLResponse
|
| 3 |
+
from fastapi.templating import Jinja2Templates
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
import os
|
| 6 |
import uuid
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# CORS (optional but safe)
|
| 11 |
|
| 12 |
app.add_middleware(
|
| 13 |
CORSMiddleware,
|
|
|
|
| 17 |
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
+
# Templates
|
| 21 |
+
|
| 22 |
+
templates = Jinja2Templates(directory="templates")
|
| 23 |
+
|
| 24 |
UPLOAD_DIR = "uploads"
|
| 25 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 26 |
|
| 27 |
+
# Serve frontend
|
| 28 |
+
|
| 29 |
+
@app.get("/", response_class=HTMLResponse)
|
| 30 |
+
def home(request: Request):
|
| 31 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 32 |
+
|
| 33 |
+
# Upload API
|
| 34 |
|
| 35 |
@app.post("/upload")
|
| 36 |
async def upload(file: UploadFile):
|
|
|
|
| 45 |
return {"link": f"/file/{file_id}_{filename}"}
|
| 46 |
```
|
| 47 |
|
| 48 |
+
# Download API
|
| 49 |
+
|
| 50 |
@app.get("/file/{filename}")
|
| 51 |
def get_file(filename: str):
|
| 52 |
file_path = f"{UPLOAD_DIR}/{filename}"
|
|
|
|
| 58 |
return FileResponse(file_path)
|
| 59 |
```
|
| 60 |
|
| 61 |
+
# Run locally
|
| 62 |
|
| 63 |
if **name** == "**main**":
|
| 64 |
import uvicorn
|