moving files

This commit is contained in:
dm
2025-08-26 17:01:27 +03:00
parent 82671319e4
commit 0462921ee4
4 changed files with 1 additions and 7 deletions

67
app/api.py Normal file
View File

@@ -0,0 +1,67 @@
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse, PlainTextResponse
from sqlalchemy import exists
import hashlib
from . import db
import os
def compute_hash(data: bytes, algorithm="sha256") -> str:
h = hashlib.new(algorithm)
h.update(data)
return h.hexdigest()
app = FastAPI()
FILES_DIR = "./files"
@app.get("/")
def root():
return {"message": "hiii from sfs"}
@app.post("/file")
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)
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("/file/{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.get("/files/")
def get_list_of_files():
files = db.get_all_files()
return [
{
"id": f.id,
"name": f.name,
"content_type": f.content_type,
"size": f.size,
"hash": f.hash,
}
for f in files
]
@app.get("/healthchecker")
def healthchecker():
return {"message": "Howdy :3"}