post files with protection from dublicats
This commit is contained in:
37
api.py
Normal file
37
api.py
Normal 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"}
|
||||
Reference in New Issue
Block a user