Skip to content

Instantly share code, notes, and snippets.

@raykipkorir
Created December 1, 2023 13:04
Show Gist options
  • Save raykipkorir/a1a16be898a98da38d48de822c33fd07 to your computer and use it in GitHub Desktop.
Save raykipkorir/a1a16be898a98da38d48de822c33fd07 to your computer and use it in GitHub Desktop.
Example configuration for AWS s3 bucket which serves Django static and media files.
"""
Dependencies:
pip install django
pip install django-storages[s3]
pip install python-decouple
"""
# proj/settings.py
from decouple import config
USE_S3 = config("USE_S3", cast=bool, default=False)
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = config("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"
AWS_S3_REGION_NAME = config("AWS_S3_REGION_NAME")
AWS_DEFAULT_ACL = None
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
# s3 static settings
STATIC_LOCATION = "static"
STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/"
# s3 public media settings
PUBLIC_MEDIA_LOCATION = "media"
MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/"
STORAGES = {
"default": {
"BACKEND": "core.storage_backends.PublicMediaStorage",
"OPTIONS": {
# configure other storage objects here
}
},
"staticfiles":{
"BACKEND": "core.storage_backends.StaticStorage"
}
}
else:
# using local filesytem to serve static and media files
STATIC_URL = "static/"
STATIC_ROOT = "/vol/static/"
MEDIA_URL = "media/"
MEDIA_ROOT = "/vol/media/"
# proj/custom_storage_backends.py
from storages.backends.s3 import S3Storage
class StaticStorage(S3Storage):
location = "static"
default_acl = "public-read"
class PublicMediaStorage(S3Storage):
location = "media"
default_acl = "public-read"
file_overwrite = "False"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment