post files with protection from dublicats

This commit is contained in:
dm
2025-08-26 16:14:32 +03:00
parent c695d36898
commit 98aa13b5f2
2 changed files with 125 additions and 0 deletions

37
api.py Normal file
View File

@@ -0,0 +1,37 @@
from fastapi import FastAPI, File, UploadFile
from sqlalchemy import exists
import hashlib
import db
def compute_hash(data: bytes, algorithm="sha256") -> str:
h = hashlib.new(algorithm)
h.update(data)
return h.hexdigest()
app = FastAPI()
@app.get("/")
def root():
return {"message": "hiii from sfs"}
@app.post("/")
async def save_file(file: UploadFile = File(...)):
contents = await file.read()
hash = compute_hash(contents)
existed_url = db.file_exists(file.size, hash)
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:
f.write(contents)
return {"status": "saved", "filename": file_url}
else:
return {"status": "file_exists", "filename": existed_url}
@app.get("/api/healthchecker")
def healthchecker():
return {"message": "Howdy :3"}