指着多个S3桶中s3boto多个、s3boto

2023-09-11 08:29:25 作者:删除回忆录

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.py collectstatic ,它的所有上传的静态文件到我的水桶。但是,我有我用于不同的目的,并希望在网站的某些地区使用,例如,如果我有这样一个模型的另一个斗:

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')

现在,当 Image.save()被调用时,它仍然会在上传文件到S3存储 AWS_STORAG​​E_BUCKET_NAME ,但是,我希望这个 Image.save()是一点到另一点S3桶。任何洁净这样做的方法是什么?我不想改变 settings.py 在运行时也没有实施违反Django的,即有一个可插拔易于改变后端存储的关键原则的做法。

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.

推荐答案

你最彻底的方法是创建S3BotoStorage的一个子类,并在init方法覆盖默认斗名。

The cleanest way for you would be to create a subclass of S3BotoStorage, and override default bucket name in the init method.

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

class MyS3Storage(S3BotoStorage):
    def __init__(self, *args, **kwargs):
        kwargs['bucket'] = getattr(settings, 'MY_AWS_STORAGE_BUCKET_NAME')
        super(MyS3Storage, self).__init__(*args, **kwargs)

然后指定这个类作为你的 DEFAULT_FILE_STORAG​​E 离开 STATICFILES_STORAG​​E ,因为它是,反之亦然。

Then specify this class as your DEFAULT_FILE_STORAGE and leave STATICFILES_STORAGE as it is, or vise versa.