added .env + delete file + handle error when file didns saved but added to db
This commit is contained in:
26
app/api.py
26
app/api.py
@@ -4,6 +4,10 @@ from sqlalchemy import exists
|
||||
import hashlib
|
||||
from . import db
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
load_dotenv()
|
||||
FILES_DIR = os.getenv("FILES_DIR")
|
||||
|
||||
def compute_hash(data: bytes, algorithm="sha256") -> str:
|
||||
h = hashlib.new(algorithm)
|
||||
@@ -12,7 +16,6 @@ def compute_hash(data: bytes, algorithm="sha256") -> str:
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
FILES_DIR = "./files"
|
||||
|
||||
@app.get("/")
|
||||
def root():
|
||||
@@ -29,10 +32,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)
|
||||
|
||||
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}
|
||||
try:
|
||||
with open(f"{FILES_DIR}/{file_url}", "wb") as f:
|
||||
f.write(contents)
|
||||
return {"status": "saved", "filename": file_url}
|
||||
except Exception as e:
|
||||
db.remove_file(file_url)
|
||||
return {"status": "error", "message": f"Could not save file {file_url}: {e}"}
|
||||
else:
|
||||
return {"status": "file_exists", "filename": existed_url}
|
||||
|
||||
@@ -48,6 +54,16 @@ def get_file(filename: str, raw: bool = False):
|
||||
|
||||
return FileResponse(file_path, filename=filename)
|
||||
|
||||
|
||||
@app.delete("/file/{filename}")
|
||||
def delete_file(filename: str):
|
||||
if db.remove_file(filename):
|
||||
file_path = f"{FILES_DIR}/{filename}"
|
||||
if os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
return {"status": "deleted"}
|
||||
return {"status": "error", "message": "no file like that"}
|
||||
|
||||
@app.get("/files/")
|
||||
def get_list_of_files():
|
||||
files = db.get_all_files()
|
||||
|
||||
Reference in New Issue
Block a user