Skip to main content
 首页 » 编程设计

python之Django之用户在 View 中上传 S3 文件

2025年05月04日41JeffreyZhao

我有一个页面,用户可以在其中将 PDF/图像文件上传到他们的个人资料。这些文件的模型相对简单:

class ResumeItemFile(models.Model): 
    item = models.ForeignKey(ResumeItem, related_name='attachment_files') 
    file = models.FileField( 
    max_length=255, upload_to=RandomizedFilePath('resume_attachments'), 
    verbose_name=_('Attachment')) 
    name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) 

我正在创建一个 View ,其中链接到配置文件 (item) 的所有文件都收集在一个 .zip 文件中。我已经在本地运行了,但在生产环境中,我遇到了以下错误 NotImplementedError: This backend doesn't support absolute paths.

主要区别在于在生产环境中,媒体文件是通过 S3 提供的

MEDIA_URL = 'https://******.s3.amazonaws.com/' 
STATIC_URL = MEDIA_URL 
 
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' 
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' 

在我看来,我在 attachments 变量中创建了一个 ResumeItemFile 列表,它是一个看起来像这样的字典列表:{'filename', ResumeItemFileObject}

            for file in attachments: 
 
                storage = DefaultStorage() 
                filename = file[1] 
                file_extension = str(file[0].file).split('.')[-1] 
                file_object = storage.open(file[0].file.path, mode='rb')                    
                filename, file_object.read()) 
                file_object.close() 

虽然这在本地运行良好,但在暂存时它会在 file_object = storage.open(file[0].file.path, mode='rb') 行崩溃。

如果后端不支持绝对路径,我该如何选择正确的文件?有谁知道我做错了什么?

请您参考如下方法:

我认为这个问题是因为在 s3boto 存储类中,没有实现 path() 方法。根据 Django 文档,

For storage systems that aren’t accessible from the local filesystem, this will raise NotImplementedError instead.

在代码中使用 file.name 而不是 file.path。

# file_object = storage.open(file[0].file.path, mode='rb')     
file_object = storage.open(file[0].file.name, mode='rb')