【问题标题】:Static Files not saving on S3 bucket using cookiecutter-django静态文件未使用 cookiecutter-django 保存在 S3 存储桶上
【发布时间】:2020-03-13 11:37:46
【问题描述】:

我正在尝试在 Heroku 上部署我的项目。我在部署后运行了heroku run python3 manage.py collectstatic

我有这个 config/base.py

STATIC_ROOT = str(ROOT_DIR("staticfiles"))
STATIC_URL = "/static/"
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

这是config/production.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS += ["storages"]  # noqa F405
AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME")
AWS_QUERYSTRING_AUTH = False
_AWS_EXPIRY = 60 * 60 * 24 * 7
AWS_S3_OBJECT_PARAMETERS = {
"CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate"
}
AWS_DEFAULT_ACL = None
AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None)
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

from storages.backends.s3boto3 import S3Boto3Storage  # noqa E402


class StaticRootS3Boto3Storage(S3Boto3Storage):
    location = "static"
    default_acl = "public-read"


class MediaRootS3Boto3Storage(S3Boto3Storage):
    location = "media"
    file_overwrite = False

DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage"
MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/"

这些是我的 heroku 环境变量

我使用 cookiecutter-django 生成了这个。在我的本地主机上一切正常,但是当我将它部署到 heroku 时,它不会保存静态文件。

【问题讨论】:

    标签: django amazon-s3 django-staticfiles cookiecutter-django


    【解决方案1】:

    与其将资产上传到 S3,不如使用白噪声来提供静态文件会更容易。基本上 whitenoise 允许您从 django 应用程序而不是其他地方提供静态文件。

    使用 pip install 安装 whitenoise。 pip install whitenoise.

    您需要包含 whitenoise 作为中间件。

    MIDDLEWARE = [
      'django.middleware.security.SecurityMiddleware',
      'whitenoise.middleware.WhiteNoiseMiddleware',
      # ...
    ]
    

    在开发模式下使用白噪声。您需要一个已安装的应用程序。

    INSTALLED_APPS = [
        'whitenoise.runserver_nostatic',
        'django.contrib.staticfiles',
        # ...
    ]
    

    就是这样!您可以在文档中阅读更多信息。 http://whitenoise.evans.io/en/stable/django.html

    为了提高性能,您可以将其配置为使用 CDN,但如果它只是一个小型站点,则没有必要。

    【讨论】:

    • 你不需要两者。所以没有理由两者兼得。
    • 我认为@Jonathan 是对的:对于生产,您只需要中间件,对于开发,您需要添加应用程序whitenoise.runserver_nostatic
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2017-09-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多