Django-compressor: how to write to S3, read from CloudFront?

前端 未结 6 1283
失恋的感觉
失恋的感觉 2020-12-12 19:52

I want to serve my compressed CSS/JS from CloudFront (they live on S3), but am unable to work out how to do it via the compressor settings in settings.py, I have the followi

6条回答
  •  情话喂你
    2020-12-12 20:26

    I wrote a wrapper storage backend around the one provided by boto

    myapp/storage_backends.py:

    import urlparse
    from django.conf import settings
    from storages.backends.s3boto import S3BotoStorage
    
    def domain(url):
        return urlparse.urlparse(url).hostname    
    
    class MediaFilesStorage(S3BotoStorage):
        def __init__(self, *args, **kwargs):
            kwargs['bucket'] = settings.MEDIA_FILES_BUCKET
            kwargs['custom_domain'] = domain(settings.MEDIA_URL)
            super(MediaFilesStorage, self).__init__(*args, **kwargs)
    
    class StaticFilesStorage(S3BotoStorage):
        def __init__(self, *args, **kwargs):
            kwargs['bucket'] = settings.STATIC_FILES_BUCKET
            kwargs['custom_domain'] = domain(settings.STATIC_URL)
            super(StaticFilesStorage, self).__init__(*args, **kwargs)
    

    Where my settings.py file has...

    STATIC_FILES_BUCKET = "myappstatic"
    MEDIA_FILES_BUCKET = "myappmedia"
    STATIC_URL = "http://XXXXXXXX.cloudfront.net/"
    MEDIA_URL = "http://XXXXXXXX.cloudfront.net/"
    
    DEFAULT_FILE_STORAGE = 'myapp.storage_backends.MediaFilesStorage'
    COMPRESS_STORAGE = STATICFILES_STORAGE = 'myapp.storage_backends.StaticFilesStorage'
    

提交回复
热议问题