【问题标题】:Move Files with S3BotoStorage使用 S3BotoStorage 移动文件
【发布时间】:2018-04-28 03:24:15
【问题描述】:

我正在使用来自django-storages 的S3BotoStorage 为我的 Django 后端处理我的 S3 存储桶上的媒体和静态文件。

一切都按预期工作,但后端引发 not ImplementedError,因为当我在 Image 是 models.Image 字段的地方调用 self.image.path 时,它不是本地文件系统。这是expected behavior。

但是,我使用路径来移动带有 os.rename 的图像(这也不适用于我的存储桶)。在存储桶上移动该文件的方法是什么?

【问题讨论】:

    标签: python django amazon-s3 boto3 django-storage


    【解决方案1】:

    您应该使用storage,而不是使用os 来移动您的文件

    要移动您的文件,您可以在您的FileField(或在本例中为ImageField)上使用read() 方法,(并最终使用storage 删除旧文件)。

    file_content = my_model.my_image.read()
    file_name = my_model.my_image.name
    
    # Renaming the file
    my_model.my_image = my_model.my_image.save('new_file_name', ContentFile(file_content))
    
    # If you want to delete the original file afterwards:
    from django.core.files.storage import default_storage
    default_storage.delete(file_name)
    

    【讨论】:

    • 对于像图像这样的大文件来说,这可能是一个计算密集型的操作吧?
    猜你喜欢
    • 2022-01-15
    • 2011-02-26
    • 2018-10-07
    • 2020-07-19
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多