django-storages icon indicating copy to clipboard operation
django-storages copied to clipboard

Add content_type to the object param function

Open aljazkosir opened this issue 3 years ago • 3 comments

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.

aljazkosir avatar Oct 14 '21 16:10 aljazkosir

Couldn't you accomplish this by looking at the name?

if name.lower().endswith('.pdf')

jschneier avatar Oct 15 '21 04:10 jschneier

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.

aljazkosir avatar Oct 15 '21 09:10 aljazkosir

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.

jschneier avatar Aug 09 '22 13:08 jschneier

Sorry will ask that you use the logic like in mimetypes to accomplish this.

jschneier avatar Aug 26 '23 21:08 jschneier