Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created December 20, 2022 23:28
Show Gist options
  • Save rg3915/c0bde21cb279c492b2fe3dbf98749f77 to your computer and use it in GitHub Desktop.
Save rg3915/c0bde21cb279c492b2fe3dbf98749f77 to your computer and use it in GitHub Desktop.
AWS S3 storage config
pip install python-decouple  # variaveis de ambiente
pip install django-storages  # storage
cat << EOF > .env
AWS_ACCESS_KEY_ID=**********
AWS_SECRET_ACCESS_KEY=****************
AWS_STORAGE_BUCKET_NAME=brejinho
EOF
echo ".env" >> .gitignore
# storage_backends.py
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage


class MediaStorage(S3Boto3Storage):
    '''
    Público
    '''
    location = 'media'
    file_overwrite = False


class PrivateMediaStorage(S3Boto3Storage):
    location = settings.AWS_PRIVATE_MEDIA_LOCATION
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False
# settings.py
INSTALLED_APPS = [
    ...
    'storages',
    ...
]

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 = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

# AWS_PRIVATE_MEDIA_LOCATION = 'media/private'

# Público
DEFAULT_FILE_STORAGE = 'backend.storage_backends.MediaStorage'

# Privado
# PRIVATE_FILE_STORAGE = 'backend.storage_backends.PrivateMediaStorage'
# models.py
class Foto(models.Model):
    documento = models.FileField(
        storage=MediaStorage(),
        # storage=PrivateMediaStorage(),
        null=True,
        blank=True
    )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment