指向 s3boto 中的多个 S3 存储桶
在 settings.py
中,我有:
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxx'
AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxx'
AWS_STORAGE_BUCKET_NAME = 'static.mysite.com'
这指向我的 S3 存储桶 static.mysite.com
,并且当我执行 manage.pycollectstatic
时工作正常,它将所有静态文件上传到我的存储桶中。但是,我有另一个存储桶,用于不同的目的,并且希望在网站的某些区域中使用,例如,如果我有这样的模型:
class Image(models.Model):
myobject = models.ImageField(upload_to='my/folder')
现在,当调用 Image.save()
时,它仍会将文件上传到 AWS_STORAGE_BUCKET_NAME
中的 S3 存储桶,但我希望此 Image.save()
指向另一个 S3 存储桶。有什么干净方法可以做到这一点吗?我不想在运行时更改 settings.py
,也不想实施任何违反 django 关键原则的做法,即具有可插拔的易于更改的后端存储。
In settings.py
I have:
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxx'
AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxx'
AWS_STORAGE_BUCKET_NAME = 'static.mysite.com'
This is pointing to my S3 bucket static.mysite.com
and works fine when I do manage.py collectstatic
, it uploads all the static files to my bucket. However, I have another bucket which I use for different purposes and would like to use in certain areas of the website, for example if I have a model like this:
class Image(models.Model):
myobject = models.ImageField(upload_to='my/folder')
Now when Image.save()
is invoked, it will still upload the file to the S3 bucket in AWS_STORAGE_BUCKET_NAME
, however I want this Image.save()
to be point to another S3 bucket. Any clean way of doing this? I don't want to change settings.py
in run time nor implement any practices that violate the key principles of django, i.e. having a pluggable easy-to-change backend storage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对您来说最干净的方法是创建 S3BotoStorage 的子类,并覆盖 init 方法中的默认存储桶名称。
然后将此类指定为
DEFAULT_FILE_STORAGE
并保留STATICFILES_STORAGE
不变,反之亦然。The cleanest way for you would be to create a subclass of S3BotoStorage, and override default bucket name in the init method.
Then specify this class as your
DEFAULT_FILE_STORAGE
and leaveSTATICFILES_STORAGE
as it is, or vise versa.