将Cloudfront与Django S3Boto配合使用

时间:2015-07-11 12:49:46

标签: python django

我已成功设置我的应用程序以使用S3存储所有静态和媒体文件。但是,我想上传到S3(当前操作),但是从我设置的云端实例提供服务。我已经尝试将设置调整到cloudfront网址,但它不起作用。我如何上传到S3并从Cloudfront服务?

设置

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

DEFAULT_FILE_STORAGE = 'app.custom_storages.MediaStorage'
STATICFILES_STORAGE = 'app.custom_storages.StaticStorage'

STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'

STATIC_URL = "https://s3-eu-west-1.amazonaws.com/app/%s/" % (STATICFILES_LOCATION)
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)

custom_storages.py

from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class StaticStorage(S3BotoStorage):
    location = settings.STATICFILES_LOCATION

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION

2 个答案:

答案 0 :(得分:32)

您的代码几乎已完成,除非您没有将您的cloudfront域添加到STATIC_URL / MEDIA_URL和您的自定义存储空间。

详细说明,您必须先安装依赖项

pip install django-storages-redux boto

将所需设置添加到django设置文件

INSTALLED_APPS = (
    ...
    'storages',
    ...
)

AWS_STORAGE_BUCKET_NAME = 'mybucketname'
AWS_CLOUDFRONT_DOMAIN = 'xxxxxxxx.cloudfront.net'
AWS_ACCESS_KEY_ID = get_secret("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_secret("AWS_SECRET_ACCESS_KEY")

MEDIAFILES_LOCATION = 'media'
MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION
MEDIA_URL = '//%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'app.custom_storages.MediaStorage'

STATICFILES_LOCATION = 'static'
STATIC_ROOT = '/%s/' % STATICFILES_LOCATION
STATIC_URL = '//%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, STATICFILES_LOCATION)
STATICFILES_STORAGE = 'app.custom_storages.StaticStorage'

您的自定义存储需要进行一些修改才能显示资源的云端域,而不是S3域:

from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class StaticStorage(S3BotoStorage):
"""uploads to 'mybucket/static/', serves from 'cloudfront.net/static/'"""
    location = settings.STATICFILES_LOCATION

    def __init__(self, *args, **kwargs):
        kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN
        super(StaticStorage, self).__init__(*args, **kwargs)

class MediaStorage(S3BotoStorage):
"""uploads to 'mybucket/media/', serves from 'cloudfront.net/media/'"""
    location = settings.MEDIAFILES_LOCATION

    def __init__(self, *args, **kwargs):
        kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN
        super(MediaStorage, self).__init__(*args, **kwargs)

这就是您所需要的,假设您的存储桶和云端域正确链接且用户的AWS_ACCESS_KEY具有对您的存储桶的访问权限。此外,根据您的使用情况,您可能希望每个人都可以只读取您的s3存储桶项目。

答案 1 :(得分:2)

我遇到了类似问题,只是将AWS_S3_CUSTOM_DOMAIN设置为Django的settings.py中的Cloudfront网址。stdClass Object ( [GetPlayerResult] => stdClass Object ( [RegistrationResponses.Player] => Array (...) 为我工作。您可以查看代码here