保护一些文件存储
您上传的大部分媒体(例如用户头像)都希望公开。但是,如果您有一些需要身份验证才能访问的媒体——比如只有会员可以访问的 PDF 简历——那么你不希望 S3BotoStorage 的默认 S3 ACL 公开阅读。这里我们不必子类化,因为我们可以传入一个实例而不是引用一个类。
所以首先删除设置中所有文件字段的保护并添加缓存控制
AWS_HEADERS = {
'Cache-Control': 'max-age=86400',
}
# By default don't protect s3 urls and handle that in the model
AWS_QUERYSTRING_AUTH = False
然后使您需要保护的文件字段使用您的自定义保护路径
from django.db import models
import storages.backends.s3boto
protected_storage = storages.backends.s3boto.S3BotoStorage(
acl='private',
querystring_auth=True,
querystring_expire=600, # 10 minutes, try to ensure people won't/can't share
)
class Profile(models.Model):
resume = models.FileField(
null=True,
blank=True,
help_text='PDF resume accessible only to members',
storage=protected_storage,
)
但是当你在开发时你也需要使用你的普通存储,而且你通常使用本地存储,所以这就是我个人的做法
if settings.DEFAULT_FILE_STORAGE == 'django.core.files.storage.FileSystemStorage':
protected_storage = FileSystemStorage()
logger.debug('Using FileSystemStorage for resumes files')
else:
protected_storage = S3BotoStorage(
acl='private',
querystring_auth=True,
querystring_expire=86400, # 24Hrs, expiration try to ensure people won't/can't share after 24Hrs
)
logger.debug('Using protected S3BotoStorage for resumes files')
参考:https ://tartarus.org/james/diary/2013/07/18/fun-with-django-storage-backends