get file added

This commit is contained in:
dm
2025-08-26 16:39:14 +03:00
parent 6f315d33a2
commit 84d29ac2db

23
api.py
View File

@@ -1,7 +1,9 @@
from fastapi import FastAPI, File, UploadFile
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse, PlainTextResponse
from sqlalchemy import exists
import hashlib
import db
import os
def compute_hash(data: bytes, algorithm="sha256") -> str:
h = hashlib.new(algorithm)
@@ -10,10 +12,24 @@ def compute_hash(data: bytes, algorithm="sha256") -> str:
app = FastAPI()
FILES_DIR = "./files"
@app.get("/")
def root():
return {"message": "hiii from sfs"}
@app.get("/{filename}")
def get_file(filename: str, raw: bool = False):
file_path = os.path.join(FILES_DIR, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
if raw:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
return PlainTextResponse(f.read())
return FileResponse(file_path, filename=filename)
@app.post("/")
async def save_file(file: UploadFile = File(...)):
@@ -26,12 +42,13 @@ async def save_file(file: UploadFile = File(...)):
if not existed_url:
file_url = db.add_file(file.filename, file.content_type, file.size, hash)
with open(f"files/{file.filename}", "wb") as f:
print(f"{FILES_DIR}/{file_url}")
with open(f"{FILES_DIR}/{file_url}", "wb") as f:
f.write(contents)
return {"status": "saved", "filename": file_url}
else:
return {"status": "file_exists", "filename": existed_url}
@app.get("/api/healthchecker")
@app.get("/healthchecker")
def healthchecker():
return {"message": "Howdy :3"}