Как изменить имя файла django InMemoryUploadedFile перед загрузкой на S3 без моделей?

Окружающая среда

Django==3.24

DRF==3.11

boto3==1.16

django-storages==1.10


Я хочу изменить имя файлов перед загрузкой на s3 без сохранения в DB(model).

Я попробовал вот так.

# in Post request
files = request.FILES.getlist('files')

res = []

for file in files:
    random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
    ext = file.name.split('.')[-1]
    file_name = f'{random_car}.{ext}'

    # -------- try start ---------
    # I want to change file name to file_name
    # This code throws an error.
    # FileNotFoundError: [Errno 2] No such file or directory: '8.jpeg' -> 'kVuepnuR.jpeg'
    os.rename(file.name, file_name)
    # -------- try end ---------

    file_path_within_bucket = os.path.join(
        file_directory_within_bucket,
        file.name
    )

    default_storage.save(file_path_within_bucket, file)
    file_url = default_storage.url(file_path_within_bucket)

    res.append(file_url)

Как я могу изменить имя файла InMemoryUploadedFile?

Я нашел способ решить ее и делюсь этим.

random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
ext = file.name.split('.')[-1]
file_name = f'{random_car}.{ext}'

file_path_within_bucket = os.path.join(
    file_directory_within_bucket,
    f"{file_name}"
)

руководить

random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
ext = file.name.split('.')[-1]
file_name = f'{random_car}.{ext}'


file_path_within_bucket = os.path.join(
    file_directory_within_bucket,
    file.name
)
Вернуться на верх