静态文件未使用cookiecutter-django保存在S3存储桶中

时间:2019-11-18 06:08:21

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

我正在尝试在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 env变量 enter image description here

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

1 个答案:

答案 0 :(得分: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,但是如果它只是一个小型站点,则没有必要。