我希望根据我的文件类型和文件名模式选择性地应用AWS标头,同时将它们上传到S3源。我正在使用django-storage与django 1.8.12
我可以在django-storages documentation中看到设置AWS_HEADERS,但我似乎无法找到在某些文件上应用此设置的方法。 如果有人可以指导我,我将不胜感激
答案 0 :(得分:1)
# handlers.py
import mimetypes
from storages.backends.s3boto import S3BotoStorage
from django.conf import settings
class ManagedS3BotoStorage(S3BotoStorage):
def _save(self, name, content):
cleaned_name = self._clean_name(name)
_type, encoding = mimetypes.guess_type(name)
content_type = getattr(content, 'content_type',
_type or self.key_class.DefaultContentType)
self.headers.update(self.get_headers(cleaned_name, content_type))
return super(ManagedS3Storage, self)._save(name, content)
def get_headers(cleaned_name, content_type):
// if possible, load AWS_HEADERS_LIST from settings
headers_list = settings.AWS_HEADERS_LIST
// logic for updating headers & return headers
settings.py文件中的#changes
DEFAULT_FILE_STORAGE = 'handlers.ManagedS3BotoStorage'
答案 1 :(得分:0)
其他答案大约为S3BotoStorage
,此答案大约为S3Boto3Storage
(请注意3
之后的Boto
。您需要覆盖_save_content
,如下所示:
class CustomBoto3Storage(S3Boto3Storage):
def _save_content(self, obj, content, parameters):
"""We want .mp3 files to have the Content-Disposition header set to
attachement in this example."""
new_parameters = parameters.copy() if parameters else {}
if new_parameters.get('ContentType') in ['audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg']:
new_parameters['ContentDisposition'] = 'attachment'
return super()._save_content(obj, content, new_parameters)