More image changes. Delete and replacement logic.

This commit is contained in:
Yaro Kasear 2025-07-11 14:03:16 -05:00
parent 7d96839af8
commit 48ad5847b9
9 changed files with 67 additions and 30 deletions

View file

@ -1,4 +1,5 @@
import hashlib
import os
from flask import url_for
from werkzeug.utils import secure_filename
@ -69,16 +70,14 @@ worklog_headers = {
def link(text, endpoint, **values):
return {"text": text, "url": url_for(endpoint, **values)}
def generate_hashed_filename(file_storage, model_name: str) -> str:
# Hash file contents
file_bytes = file_storage.read()
sha = hashlib.sha256(file_bytes).hexdigest()
# Reset the stream so Flask can read it again later
file_storage.stream.seek(0)
def generate_hashed_filename(file) -> str:
content = file.read()
file.seek(0) # Reset after reading
original_name = secure_filename(file_storage.filename)
return f"{model_name}/{sha}_{original_name}"
hash = hashlib.sha256(content).hexdigest()
ext = os.path.splitext(file.filename)[1]
return f"{hash}_{file.filename}"
def get_image_attachable_class_by_name(name: str):
for cls in ImageAttachable.__subclasses__():

View file

@ -12,19 +12,11 @@ image_bp = Blueprint("image_api", __name__)
def save_image(file, model: str) -> str:
assert current_app.static_folder
hashed_name = generate_hashed_filename(file, model)
rel_path = posixpath.join("uploads", "images", hashed_name)
abs_path = os.path.join(current_app.static_folder, "uploads", "images", rel_path)
filename = generate_hashed_filename(file)
rel_path = posixpath.join("uploads", "images", model, filename)
abs_path = os.path.join(current_app.static_folder, rel_path)
dir_path = os.path.dirname(abs_path)
if not os.path.exists(dir_path):
os.makedirs(dir_path, exist_ok=True)
print("Saving file:")
print(" - Model:", model)
print(" - Relative path:", rel_path)
print(" - Absolute path:", abs_path)
print(" - Directory exists?", os.path.exists(dir_path))
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
file.save(abs_path)
return rel_path
@ -86,3 +78,11 @@ def delete_image(image_id):
image = db.session.get(Image, image_id)
if not image:
return jsonify({"success": False, "error": "Image not found"})
abs_path = os.path.join(current_app.static_folder, image.filename.replace("\\", "/"))
if os.path.exists(abs_path):
os.remove(abs_path)
db.session.delete(image)
db.session.commit()
return jsonify({"success": True})