aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2024-01-16 12:33:04 +0300
committerFrederick Muriuki Muriithi2024-01-16 12:33:04 +0300
commit7d6deb76edde8dce5414220586c1fde0ddebfc6e (patch)
tree06c30cd74a12c31100701c0573754ebac9e064be
parent0b8bd607645bf32e1713841e4c68dbc7ea60c0a2 (diff)
downloadgn-uploader-7d6deb76edde8dce5414220586c1fde0ddebfc6e.tar.gz
Build a sha512 hash from the uploaded file's name and timestamp
Build a sha512 message digest from the file's name and the timestamp of when the file was uploaded. This ensures that the filename is URL-safe, and reduces chances of name conflicts in the upload directory which could lead to data corruption when processing the files and saving the files into the database.
-rw-r--r--qc_app/files.py7
1 files changed, 6 insertions, 1 deletions
diff --git a/qc_app/files.py b/qc_app/files.py
index 0304296..205a39c 100644
--- a/qc_app/files.py
+++ b/qc_app/files.py
@@ -1,6 +1,8 @@
"""Utilities to deal with uploaded files."""
+import hashlib
from pathlib import Path
from typing import Union
+from datetime import datetime
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
@@ -9,7 +11,10 @@ def save_file(fileobj: FileStorage, upload_dir: Path) -> Union[Path, bool]:
"""Save the uploaded file and return the path."""
if not bool(fileobj):
return False
- filename = Path(secure_filename(fileobj.filename)) # type: ignore[arg-type]
+ hashed_name = hashlib.sha512(
+ f"{fileobj.filename}::{datetime.now().isoformat()}".encode("utf8")
+ ).hexdigest()
+ filename = Path(secure_filename(hashed_name)) # type: ignore[arg-type]
if not upload_dir.exists():
upload_dir.mkdir()