How to configure django-compressor and django-staticfiles with Amazon's S3?

前端 未结 4 1704
遇见更好的自我
遇见更好的自我 2021-02-01 03:51

I\'m trying to setup django-compressor and django-staticfiles so that the compressed CSS/Javascript and images are served from Amazon\'s S3.

I\'ve managed to setup stati

4条回答
  •  孤街浪徒
    2021-02-01 04:06

    After plenty of days of hard work and research I was finally able to do this and I decided to write a detailed guide about it, including how to also serve them zipped with gzip.

    Basically you need to do a few things:

    1. Use AWS_IS_GZIPPED = True
    2. If your S3 is outside of US. You need to create a custom S3Connection class where you override the DefaultHost variable to your S3 url. Example s3-eu-west-1.amazonaws.com
    3. If you're using a dotted bucket name, example subdomain.domain.tld. You need to set AWS_S3_CALLING_FORMAT = 'boto.s3.connection.OrdinaryCallingFormat'
    4. You have to set non_gzipped_file_content = content.file in your CachedS3BotoStorage

    This is the CachedS3BotoStorage class you need:

    class CachedS3BotoStorage(S3BotoStorage):
        """
        S3 storage backend that saves the files locally, too.
        """
        connection_class = EUConnection
        location = settings.STATICFILES_LOCATION
        def __init__(self, *args, **kwargs):
            super(CachedS3BotoStorage, self).__init__(*args, **kwargs)
            self.local_storage = get_storage_class(
                "compressor.storage.CompressorFileStorage")()
    
    def save(self, name, content):
        non_gzipped_file_content = content.file
        name = super(CachedS3BotoStorage, self).save(name, content)
        content.file = non_gzipped_file_content
        self.local_storage._save(name, content)
        return name
    

    Note that EUConnection is a custom class where I set DefaultHost to my S3 location. Check the much longer and detailed guide for complete custom storages and settings.py

提交回复
热议问题