Skip to content

Instantly share code, notes, and snippets.

@adrianomargarin
Last active September 2, 2018 22:44
Show Gist options
  • Save adrianomargarin/31f7163d6e24c2e0e27eb20bf6959f11 to your computer and use it in GitHub Desktop.
Save adrianomargarin/31f7163d6e24c2e0e27eb20bf6959f11 to your computer and use it in GitHub Desktop.
Upload de arquivos para AWS S3
DEFAULT_FILE_STORAGE=yourproject.storage.MediaStorage
STATICFILES_STORAGE=yourproject.storage.StaticStorage
STATIC_AWS_BUCKET=yourproject-static
MEDIA_AWS_BUCKET=yourproject-media
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-access-key
import os
from uuid import uuid4
from django.db import models
def get_storage_path(instance, filename, subdir):
_, ext = os.path.splitext(filename)
new_name = '{}{}'.format(str(uuid4()), ext)
return os.path.join('your-path', subdir, new_name)
def get_image_storage_path(instance, filename):
return get_storage_path(instance, filename, 'your-name')
class MyModel(models.Model):
image = models.ImageField(upload_to=get_image_storage_path)
INSTALLED_APPS = [
#...
'storages', # pip install django-storages
]
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID', default='')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY', default='')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME', default='')
AWS_QUERYSTRING_AUTH = False
STATIC_URL = '/static/'
STATIC_AWS_BUCKET = config('STATIC_AWS_BUCKET', default='')
STATICFILES_STORAGE = config('STATICFILES_STORAGE', default='django.contrib.staticfiles.storage.StaticFilesStorage')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'yourproject/yourapp/static')
)
MEDIA_URL = '/media/'
MEDIA_AWS_BUCKET = config('MEDIA_AWS_BUCKET', default='')
DEFAULT_FILE_STORAGE = config('DEFAULT_FILE_STORAGE', default='django.core.files.storage.FileSystemStorage')
if DEFAULT_FILE_STORAGE == 'django.core.files.storage.FileSystemStorage':
MEDIA_ROOT = os.path.join(BASE_DIR, 'yourproject', 'media')
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
bucket_name = settings.STATIC_AWS_BUCKET
class MediaStorage(S3Boto3Storage):
bucket_name = settings.MEDIA_AWS_BUCKET
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment