带有多个 S3 存储桶的 django 存储 [英] django-storages with multiple S3 Buckets

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

问题描述

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

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

我看到了这个 Django - 导入 storages.backends 时出错,但我没有不明白应该怎么用?!

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

推荐答案

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

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

编辑:

评论已经失控,所以我会更新我的答案.在实例的基础上更改存储后端的参数并不是 Django 存储 API 旨在做的事情.存储后端不知道模型实例,因为存储可以在模型上下文之外使用,例如静态文件.并非完全不合理,但这不是 Django 或 django-storages 旨在解决的用法.我不希望您会发现可以为您处理此问题的存储后端下降.

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.

文档描述了如何手动管理文件:https://docs.djangoproject.com/en/1.9/topics/files/#storage-objects 至少您需要将保存文件的存储桶存储在某处,以便稍后查询模型时可以找到它.

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.

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

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