WMGZON/utils/file_utils.py

47 lines
1.3 KiB
Python

import os
import uuid
import pathlib
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename) -> bool:
""" Ensures only filenames ending with the correct extension are allowed.
Note: This does not verify that the content inside of the file
matches the type specified
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def save_image(file) -> str | None:
""" Saves a given file to disk with a random UUID4 generated
filename. Returns the filename as a string.
"""
# Ensure that the correct file type is uploaded
if file is None or not allowed_file(file.filename):
return None
# Create the product object and push to database
filename = str(uuid.uuid4()) + pathlib.Path(file.filename).suffix
path = os.environ.get('FILESTORE')
file.save(os.path.join(path, filename))
return filename
def create_directory(dir: str):
""" Creates the given directory string is not alreay made """
try:
os.makedirs(dir)
except FileExistsError:
pass
def remove_file(dir: str):
""" Removes a given file if it is present at the given dir """
try:
os.remove(dir)
except FileNotFoundError:
pass