Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectively apply AWS Headers while uploading static files using django-storages

I want to selectively apply AWS headers based on my file type and filename pattern while uploading them to S3 origin. I am using django-storages with django 1.8.12

I can see the setting AWS_HEADERS in django-storages documentation, but I can't seem to find a way to apply this setting on some files only. I would appreciate if someone can guide me on this

like image 921
Anurag Avatar asked Oct 28 '25 21:10

Anurag


1 Answers

The simplest is to subclass storages.backends.s3boto.S3BotoStorage to introduce the required behavior

from storages.backends.s3boto import S3BotoStorage

class MyS3Storage(S3BotoStorage):

    def _save(self, name, content):
        cleaned_name = self._clean_name(name)
        name = self._normalize_name(cleaned_name)

        _type, encoding = mimetypes.guess_type(name)
        content_type = getattr(content, 'content_type',
                           _type or self.key_class.DefaultContentType)

        # setting the content_type in the key object is not enough.
        self.headers.update({'Content-Type': content_type})


        if re.match('some pattern', cleaned_name) :
            self.headers.update({'new custome header': 'value'})

        if content_type == 'my/content_type':
            self.headers.update({'new custome header': 'value'})

        return super(MyS3Storage, self)._save(name, content)

Don't forget to edit settings and change the file storage definition.

DEFAULT_FILE_STORAGE = 'myapp.MyS3Storage'

The above code is mainly from the S3BotoStorage class with our code merely inspecting the content type and name to add the custom headers.

like image 124
e4c5 Avatar answered Oct 31 '25 13:10

e4c5