get file added
This commit is contained in:
23
api.py
23
api.py
@@ -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
|
from sqlalchemy import exists
|
||||||
import hashlib
|
import hashlib
|
||||||
import db
|
import db
|
||||||
|
import os
|
||||||
|
|
||||||
def compute_hash(data: bytes, algorithm="sha256") -> str:
|
def compute_hash(data: bytes, algorithm="sha256") -> str:
|
||||||
h = hashlib.new(algorithm)
|
h = hashlib.new(algorithm)
|
||||||
@@ -10,10 +12,24 @@ def compute_hash(data: bytes, algorithm="sha256") -> str:
|
|||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
FILES_DIR = "./files"
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def root():
|
def root():
|
||||||
return {"message": "hiii from sfs"}
|
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("/")
|
@app.post("/")
|
||||||
async def save_file(file: UploadFile = File(...)):
|
async def save_file(file: UploadFile = File(...)):
|
||||||
@@ -26,12 +42,13 @@ async def save_file(file: UploadFile = File(...)):
|
|||||||
if not existed_url:
|
if not existed_url:
|
||||||
file_url = db.add_file(file.filename, file.content_type, file.size, hash)
|
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)
|
f.write(contents)
|
||||||
return {"status": "saved", "filename": file_url}
|
return {"status": "saved", "filename": file_url}
|
||||||
else:
|
else:
|
||||||
return {"status": "file_exists", "filename": existed_url}
|
return {"status": "file_exists", "filename": existed_url}
|
||||||
|
|
||||||
@app.get("/api/healthchecker")
|
@app.get("/healthchecker")
|
||||||
def healthchecker():
|
def healthchecker():
|
||||||
return {"message": "Howdy :3"}
|
return {"message": "Howdy :3"}
|
||||||
|
|||||||
Reference in New Issue
Block a user