blob: 205a39c0d5605022508b948e90de44aff4ecf965 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
"""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
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
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()
filepath = Path(upload_dir, filename)
fileobj.save(filepath)
return filepath
|