在python中为文件名(amazon S3)添加动态内容处置 [英] Add Dynamic Content Disposition for file names(amazon S3) in python

查看:58
本文介绍了在python中为文件名(amazon S3)添加动态内容处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,将文件名另存为"uuid4().pdf".其中uuid4为创建的每个实例生成一个随机的uuid.该文件名也以相同的名称存储在amazon s3服务器上.

I have a Django model that saves filename as "uuid4().pdf". Where uuid4 generates a random uuid for each instance created. This file name is also stored on the amazon s3 server with the same name.

我正在尝试为上传到Amazon s3的文件名添加自定义配置,这是因为每当我下载文件而不是uuid时,我都希望看到一个自定义名称.同时,我希望文件以uuid文件名存储在s3上.

I am trying to add a custom disposition for filename that i upload to amazon s3, this is because i want to see a custom name whenever i download the file not the uuid one. At the same time, i want the files to stored on s3 with the uuid filename.

因此,我正在使用 django-storages 使用python 2.7.我尝试过在这样的设置中添加content_disposition:

So, I am using django-storages with python 2.7. I have tried adding content_disposition in settings like this:

AWS_CONTENT_DISPOSITION = 'core.utils.s3.get_file_name'

其中get_file_name()返回文件名.

where get_file_name() returns the filename.

我还尝试将其添加到设置中:

I have also tried adding this to the settings:

AWS_HEADERS = {
'Content-Disposition': 'attachments; filename="%s"'% get_file_name(),

 }

没有运气!

您认识的人中有没有实现过此目标?

Do anyone of you know to implement this.

推荐答案

django-storages中的S3Boto3Storage当前版本支持 AWS_S3_OBJECT_PARAMETERS 全局设置变量,该变量也允许修改 ContentDisposition .但是问题在于,它按原样应用于所有上载到s3的对象,而且会影响使用该存储的所有模型,这可能不是预期的结果.

Current version of S3Boto3Storage from django-storages supports AWS_S3_OBJECT_PARAMETERS global settings variable, which allows modify ContentDisposition too. But the problem is that it is applied as is to all objects that are uploaded to s3 and, moreover, affects all models working with the storage, which may turn to be not the expected result.

以下hack对我有用.

The following hack worked for me.

from storages.backends.s3boto3 import S3Boto3Storage

class DownloadableS3Boto3Storage(S3Boto3Storage):

    def _save_content(self, obj, content, parameters):
        """
        The method is called by the storage for every file being uploaded to S3.
        Below we take care of setting proper ContentDisposition header for
        the file.
        """
        filename = obj.key.split('/')[-1]
        parameters.update({'ContentDisposition': f'attachment; filename="{filename}"'})
        return super()._save_content(obj, content, parameters)

这里,我们重写了存储对象的本机保存方法,并确保在每个文件上设置了正确的内容处置.当然,您需要将此存储提供给您正在处理的字段:

Here we override native save method of the storage object and make sure proper content disposition is set on each file. Of courese, you need to feed this storage to the field you working on:

my_file_filed = models.FileField(upload_to='mypath', storage=DownloadableS3Boto3Storage())

这篇关于在python中为文件名(amazon S3)添加动态内容处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆