指向 s3boto 中的多个 S3 存储桶

发布于 2025-01-03 18:29:11 字数 850 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

⒈起吃苦の倖褔 2025-01-10 18:29:11

对您来说最干净的方法是创建 S3BotoStorage 的子类,并覆盖 init 方法中的默认存储桶名称。

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_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.

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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文