gpt4 book ai didi

python - 将 Cloudfront 与 Django S3Boto 一起使用

转载 作者:IT老高 更新时间:2023-10-28 20:52:08 25 4
gpt4 key购买 nike

我已成功将我的应用设置为使用 S3 存储所有静态和媒体文件。但是,我想上传到 S3(当前操作),但从我设置的云端实例提供服务。我已尝试将设置调整为 cloudfront url,但它不起作用。请问如何上传到 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

最佳答案

您的代码几乎已完成,只是您没有将您的云端域添加到 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 存储桶项设置为可供所有人只读访问。

关于python - 将 Cloudfront 与 Django S3Boto 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com