django-storages
django-storages copied to clipboard
Add content_type to the object param function
I want to change the object parameters on a per-object basis. But I don't want the same params for every type of object. For example, I want ContentDisposition: attachment
for images, but not for PDF files.
My current workaround is this:
class MediaRootS3Boto3Storage(S3Boto3Storage):
location = "media"
file_overwrite = False
def _get_write_parameters(self, name, content=None):
params = {}
_type, encoding = mimetypes.guess_type(name)
content_type = getattr(content, 'content_type', None)
content_type = content_type or _type or self.default_content_type
params['ContentType'] = content_type
if encoding:
params['ContentEncoding'] = encoding
params.update(self.get_object_parameters_for_type(name, content_type))
if 'ACL' not in params and self.default_acl:
params['ACL'] = self.default_acl
return params
def get_object_parameters_for_type(self, name, content_type):
object_params = self.object_parameters.copy()
if 'image' in content_type:
object_params.update(
ContentDisposition='attachment'
)
return object_params
In this PR I update the get_object_parameters
so it also gets content_type
as a parameter.
Couldn't you accomplish this by looking at the name?
if name.lower().endswith('.pdf')
Couldn't you accomplish this by looking at the name?
if name.lower().endswith('.pdf')
Well yeah, I could do that, but sometimes the content_tpye
doesn't match the extension. Or the file has no extension at all.
I think it's just safer to check the actuall content_type
.
I think the idea is solid but it's not backwards compatible with people who have overridden the method. To merge this we would need to use the tools Django has developed for handling this kind of migration.
Sorry will ask that you use the logic like in mimetypes
to accomplish this.