From 1bf4347b19921027263cebc89aabe599a3e3ba61 Mon Sep 17 00:00:00 2001 From: Michael Sheinberg Date: Sun, 1 Jul 2018 11:13:30 -0400 Subject: [PATCH] Allow configuring static/media to point to S3 At time of this commit there are outstanding PRs that will fix the usage of iam roles instead of just regular accounts. See https://github.com/jschneier/django-storages/issues/282. Instead of forking the library with those changes I made a work-around by setting the problematic logic to False. Its a misleading addition since those attributes actually do get sucked in via env vars. --- securethenews/s3_storage.py | 14 ++++++++++++++ securethenews/settings/production.py | 23 +++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 securethenews/s3_storage.py diff --git a/securethenews/s3_storage.py b/securethenews/s3_storage.py new file mode 100644 index 00000000..5db60c69 --- /dev/null +++ b/securethenews/s3_storage.py @@ -0,0 +1,14 @@ +from django.conf import settings +from storages.backends.s3boto3 import S3Boto3Storage + + +class StaticStorage(S3Boto3Storage): + location = settings.AWS_S3_STATIC_PATH + access_key = False + secret_key = False + + +class MediaStorage(S3Boto3Storage): + location = settings.AWS_S3_MEDIA_PATH + access_key = False + secret_key = False diff --git a/securethenews/settings/production.py b/securethenews/settings/production.py index f4fba5a0..6aafc41d 100644 --- a/securethenews/settings/production.py +++ b/securethenews/settings/production.py @@ -30,8 +30,6 @@ } } -STATIC_ROOT = os.environ['DJANGO_STATIC_ROOT'] -MEDIA_ROOT = os.environ['DJANGO_MEDIA_ROOT'] try: es_host = os.environ.get('DJANGO_ES_HOST', 'disable') @@ -82,3 +80,24 @@ if os.environ.get('PIWIK_DOMAIN_PATH'): PIWIK_DOMAIN_PATH = os.environ.get('PIWIK_DOMAIN_PATH') PIWIK_SITE_ID = os.environ.get('PIWIK_SITE_ID', '1') + + +if os.environ.get('AWS_SESSION_TOKEN'): + INSTALLED_APPS.append('storages') # noqa: F405 + + AWS_S3_MEDIA_PATH = os.environ.get('AWS_S3_MEDIA_PATH', 'media') + AWS_S3_STATIC_PATH = os.environ.get('AWS_S3_STATIC_PATH', 'static') + AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') + AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME', 'us-east-1') + + AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') + AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') + AWS_SESSION_TOKEN = os.environ.get('AWS_SESSION_TOKEN', '') + AWS_S3_USE_SSL = True + AWS_S3_SIGNATURE_VERSION = os.environ.get("AWS_S3_SIG_VER", "s3v4") + STATICFILES_STORAGE = "securethenews.s3_storage.StaticStorage" + DEFAULT_FILE_STORAGE = "securethenews.s3_storage.MediaStorage" + +else: + STATIC_ROOT = os.environ['DJANGO_STATIC_ROOT'] + MEDIA_ROOT = os.environ['DJANGO_MEDIA_ROOT']