shimatta-kenkyusho/shimatta_kenkyusho/shimatta_modules/RandomFileName.py

19 lines
553 B
Python

import os
import uuid
from django.utils.deconstruct import deconstructible
# Ref: https://stackoverflow.com/questions/2673647/enforce-unique-upload-file-names-using-django
@deconstructible
class RandomFileName(object):
def __init__(self, path):
self.path = os.path.join(path, "%s/%s/%s%s")
def __call__(self, _, filename):
extension = os.path.splitext(filename)[1]
file_uuid = uuid.uuid4()
uuid_str = str(file_uuid)
first_char = uuid_str[0]
second_char = uuid_str[1]
return self.path % (first_char, second_char, file_uuid, extension)