Refactor file listing API to return only file names and add new API for calculating file SHA256 hash

This commit is contained in:
Vasily 2025-10-20 12:33:07 +08:00
parent cdb2eddea9
commit cf7381d85f

View File

@ -8,7 +8,9 @@ import os
import hashlib
PORT = 8051
DIRECTORY = "./data/db"
# Get the absolute path to the directory where this script is located
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DIRECTORY = os.path.join(SCRIPT_DIR, "data", "db")
# Ensure the data directory exists (if not already handled elsewhere)
os.makedirs(DIRECTORY, exist_ok=True)
@ -19,29 +21,36 @@ app = FastAPI()
class DeleteFileRequest(BaseModel):
name: str
class FileInfo(BaseModel):
name: str
hash: str
@app.post("/api/files/list", response_model=List[FileInfo])
@app.post("/api/files/list", response_model=List[str])
async def api_list_files():
"""
Lists all files and their SHA256 hashes in the data/db directory.
Lists all files in the data/db directory.
"""
try:
files_with_hashes = []
for f in os.listdir(DIRECTORY):
file_path = os.path.join(DIRECTORY, f)
if os.path.isfile(file_path) and f.endswith(".db"):
hasher = hashlib.sha256()
with open(file_path, "rb") as afile:
buf = afile.read()
hasher.update(buf)
files_with_hashes.append({"name": f, "hash": hasher.hexdigest()})
return files_with_hashes
files = [f for f in os.listdir(DIRECTORY) if os.path.isfile(os.path.join(DIRECTORY, f)) and f.endswith(".db")]
return files
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while listing files: {e}")
@app.post("/api/files/hash")
async def api_file_hash(request: DeleteFileRequest):
"""
Calculates and returns the SHA256 hash for a specific file.
"""
file_path = os.path.join(DIRECTORY, request.name)
if not os.path.exists(file_path) or not os.path.isfile(file_path):
raise HTTPException(status_code=404, detail=f"File not found: {request.name}")
try:
hasher = hashlib.sha256()
with open(file_path, "rb") as afile:
while chunk := afile.read(8192):
hasher.update(chunk)
return {"name": request.name, "hash": hasher.hexdigest()}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Could not calculate hash for file: {e}")
@app.post("/api/files/delete")
async def api_delete_file(request: DeleteFileRequest):
"""