如何使用django-storages和amazon S3将文件从一个路径复制到另一个路径?

pmo*_*niq 6 django storage amazon-s3

im = storage.open('old_path_filename', 'r')
strorage.save('new_path_with_old_filename', im)
Run Code Online (Sandbox Code Playgroud)

在我的django proect中,我使用django-storages和amazon S3作为我的静态和媒体文件.我需要用亚马逊和旧文件名中的新路径保存旧文件.你可以帮帮我吗?

rav*_*404 5

您可以使用Django ContentFile来执行此操作

from django.core.files.base import ContentFile

new_file = ContentFile(original_file.read())
new_file.name = original_file.name

example = Example()
example.file = new_file
example.save()
Run Code Online (Sandbox Code Playgroud)

  • 这是计算量非常大的。 (2认同)

小智 5

这样你就不会下载内容来保存它

# Bucket: bucket name
# Key: file path
from storages.backends.s3boto3 import S3Boto3Storage
s3 = S3Boto3Storage()

def copy(Bucket_A, Bucket_B, Key_A, Key_B):
    copy_source = {'Bucket': Bucket_A, 'Key': Key_A}
    s3.bucket.meta.client.copy(copy_source, Bucket_B, Key_B)
    s3.delete(Key_A)
    return Key_B

def move(Bucket_A, Bucket_B, Key_A, Key_B):
    copy(Bucket_A, Bucket_B, Key_A, Key_B)
    s3.delete(Key_A)
    return Key_B
Run Code Online (Sandbox Code Playgroud)