【问题标题】:Collectstatic creates empty filesCollectstatic 创建空文件
【发布时间】:2018-04-24 10:37:47
【问题描述】:

我正在尝试将应用升级到 Django 1.11,但遇到collectstatic 的问题。

旧版本:

django 1.8.17 
django-storages 1.5.1

新版本:

django 1.11.12
django-storages 1.6.6

存储:

class StaticS3BotoStorage(ManifestFilesMixin, S3BotoStorage):
    location = 'static'
    file_overwrite = True
    preload_metadata = True

class StaticS3BotoStorage(CachedFilesMixin, S3BotoStorage):
    location = 'static'
    file_overwrite = True
    preload_metadata = True

在旧版本中,collectstatic 工作正常,包括 collectstatic --clear

升级后,collectstatic --clear 失败(没有文件被删除)。 collectstatic 确实复制文件,但是,有时它会创建同一文件的两个版本。在这个特定的例子中,我得到了base.hash1.cssbase.hash2.cssbase.hash2.css 为空,因此页面打开,但未正确呈现。

如果我不使用 CachedFilesMixinManifestFilesMixincollectstatic 可以正常工作,但 clear 仍然失败。

我测试了 django 1.11 和 django-storages 的不同组合,但它们的行为似乎都一样。

其他人是否遇到过类似的问题?

【问题讨论】:

    标签: python django django-storage


    【解决方案1】:

    我们遇到了同样的问题。

    我认为,根本问题有多个问题/来源:

    • ManifestFilesMixin 使用和重用 ContentFile 对象来生成散列文件并多次保存它们。无需重置 ContentFile 对象(通过对它们调用 .seek(0))。
    • S3BotoStorage 保存这些文件,而不检查它们是否在正确的位置。将此与 FileSystemStorage 进行比较:始终通过遍历文件的 .chuncks() 从头开始​​读取文件。

    我们通过像这样覆盖 S3BotoStorage 来解决空文件问题:

    class PatchedS3StaticStorage(S3BotoStorage):
        def _save(self, name, content):
            if hasattr(content, 'seek') and hasattr(content, 'seekable') and content.seekable():
                content.seek(0)
            return super()._save(name, content)
    

    简而言之,我们在保存文件之前先查找文件的开头。

    【讨论】:

    • 我可以使用 boto3 使 collectstatic 工作,但媒体上传失败(实际上不是上传,而是缩略图创建)。所以中间解决方案是使用 boto3 进行静态,boto 用于媒体/缩略图。但是,由于内存问题(此处描述:github.com/jschneier/django-storages/issues/95),我们最终不得不停止使用 django-storages。我们有很多缩略图,它占用了太多内存。
    • 感谢@hellphil!我遇到了同样的问题,并将此答案调整为使用boto3(使用boto 和上述答案会导致其他奇怪的问题,即错误地将其他文件上传到S3)。见stackoverflow.com/questions/52309821/…
    猜你喜欢
    • 2013-01-25
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多