我对 settings.py 做了一些不同的更改
AWS_S3_CUSTOM_DOMAIN = 'XXXXXXX.cloudfront.net' #important: no "http://"
AWS_S3_SECURE_URLS = True #default, but must set to false if using an alias on cloudfront
COMPRESS_STORAGE = 'example_app.storage.CachedS3BotoStorage' #from the docs (linked below)
STATICFILES_STORAGE = 'example_app.storage.CachedS3BotoStorage'
压缩机文档
上述解决方案将文件保存在本地,并将它们上传到 s3。这让我可以离线压缩文件。如果您不使用 gzip,则上述内容应该适用于从 CloudFront 提供压缩文件。
添加gzip会增加皱纹:
设置.py
AWS_IS_GZIPPED = True
尽管在 collectstatic 期间将可压缩文件(根据存储的 css 和 js)推送到 s3 时,这会导致错误:
AttributeError:“cStringIO.StringO”对象没有属性“名称”
这是由于一些奇怪的错误与我不理解的 css/js 文件的压缩有关。这些文件我需要在本地,解压缩,而不是在 s3 上,所以如果我调整上面引用的存储子类(并在压缩器文档中提供),我可以完全避免这个问题。
新存储.py
from os.path import splitext
from django.core.files.storage import get_storage_class
from storages.backends.s3boto import S3BotoStorage
class StaticToS3Storage(S3BotoStorage):
def __init__(self, *args, **kwargs):
super(StaticToS3Storage, self).__init__(*args, **kwargs)
self.local_storage = get_storage_class('compressor.storage.CompressorFileStorage')()
def save(self, name, content):
ext = splitext(name)[1]
parent_dir = name.split('/')[0]
if ext in ['.css', '.js'] and not parent_dir == 'admin':
self.local_storage._save(name, content)
else:
filename = super(StaticToS3Storage, self).save(name, content)
return filename
然后保存了所有 .css 和 .js 文件(不包括管理文件,我从 CloudFront 提供未压缩的文件),同时将其余文件推送到 s3(并且不费心将它们保存在本地,尽管可以轻松添加 self.local_storage。 _save 行)。
但是当我运行 compress 时,我希望我压缩的 .js 和 .css 文件被推送到 s3,所以我创建了另一个 sublcas 供压缩器使用:
class CachedS3BotoStorage(S3BotoStorage):
"""
django-compressor uses this class to gzip the compressed files and send them to s3
these files are then saved locally, which ensures that they only create fresh copies
when they need to
"""
def __init__(self, *args, **kwargs):
super(CachedS3BotoStorage, self).__init__(*args, **kwargs)
self.local_storage = get_storage_class('compressor.storage.CompressorFileStorage')()
def save(self, filename, content):
filename = super(CachedS3BotoStorage, self).save(filename, content)
self.local_storage._save(filename, content)
return filename
最后,鉴于这些新的子类,我需要更新一些设置:
COMPRESS_STORAGE = 'example_app.storage.CachedS3BotoStorage' #from the docs (linked below)
STATICFILES_STORAGE = 'example_app.storage.StaticToS3Storage'
这就是我要说的。