django存储与多个S3桶 [英] django-storages with multiple S3 Buckets

查看:250
本文介绍了django存储与多个S3桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AWS,我的应用程序中将有不同的桶。我也使用Django-Storages。有没有办法指定要将文件上传到哪个(例如,作为Save()函数中的参数?)



我看到这个 Django - 导入存储空间错误,但我不明白应该如何使用?!



谢谢!

解决方案

S3BotoStorage 将bucket名称作为参数。如果没有给出,将使用 AWS_STORAGE_BUCKET_NAME 设置。这意味着如果您想使用 DEFAULT_FILE_STORAGE 的默认存储后端 S3BotoStorage ,那么它必须使用默认存储桶。 p>

但是,您也可以在字段级别分配一个存储空间:

  from django.db import models 
from storages.backends.s3boto import S3BotoStorage

class MyModel(models.Model):
file_1 = models.FileField()#使用默认存储
file_2 = models.FileField(storage = S3BotoStorage(bucket ='other-bucket'))

编辑



评论已经失控了,所以我会更新我的答案。在实例的基础上更改存储后端的参数不是Django存储API的设计目的。存储后端不了解模型实例,因为存储库可以在模型的上下文之外使用,例如使用静态文件。不完全不合理,但Django或django-storages不是用来解决的。我不希望你找到一个可以处理这个问题的存储后端。



该文档描述了如何手动管理文件: https://docs.djangoproject.com/en/1.9/topics/files/#存储对象至少您需要将存储文件的存储桶存储在某个位置,以便以后在查询模型时可以找到它。


I am using AWS and I will have different buckets in my application. I am also using Django-Storages. Is there a way to specify which bucket I want to upload the file to (for example, as a parameter in the Save() function or whatever?)

I saw this Django - Error importing storages.backends, but I don't understand how it should be used?!

Thanks!

解决方案

S3BotoStorage takes the bucket name as a parameter. If not given it will use the AWS_STORAGE_BUCKET_NAME setting. That means if you want to make S3BotoStorage the default storage backend with DEFAULT_FILE_STORAGE then it must use the default bucket.

However you can also assign a storage on a field level:

from django.db import models
from storages.backends.s3boto import S3BotoStorage

class MyModel(models.Model):
    file_1 = models.FileField() # Uses default storage
    file_2 = models.FileField(storage=S3BotoStorage(bucket='other-bucket'))

Edit:

Comments are getting out of hand so I'll update my answer. Changing the parameters of the storage backend on an instance basis is not something that the Django storage API was designed to do. The storage backend does not have knowledge of the model instance because the storages can be used outside the context of a model such as with static files. Not completely unreasonable but it's not a usage that Django or django-storages was intended to solve. I don't expect you aren to find a drop in storage backend that will handle this for you.

The docs describe how you can manage files manually: https://docs.djangoproject.com/en/1.9/topics/files/#storage-objects At a minimum you would need store the bucket where you saved the file somewhere so that you can find it later when you query the model.

这篇关于django存储与多个S3桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆