python - Django 仅在生产环境中使用私有(private) S3 存储

标签 python django amazon-s3 django-rest-framework django-storage

我已经将我的 django REST API 设置为在 Debug模式下使用本地存储,在生产环境中使用 S3 存储。这适用于公共(public)文件,因为我覆盖了 DEFAULT_FILE_STORAGE像这样:

if IS_DEBUG:
    DEFAULT_FILE_STORAGE = 'api.storage_backends.PublicMediaStorage'

和每个 FileField自动使用它。现在我想以同样的方式使用私有(private) S3 存储,但因为我必须明确定义存储 (FileField(storage=PrivateMediaStorage())),所以始终使用 S3 存储。

在 Debug模式下如何使用本地存储而不是 S3 存储?

PS:我已经考虑过将模型更改为使用 FileField根据 DEBUG 模式有或没有显式存储。这并没有完全解决我的问题,因为我的迁移是在 Debug模式下创建的,因此总是包含没有私有(private)存储类的模型。

更新:
我正在寻找一种可以在两种环境中共享相同迁移并且仅在运行时延迟实例化实际存储类的解决方案。就像 django 处理 DEFAULT_FILE_STORAGE已经。

最佳答案

最好的解决方案是使用 FileField 没有明确的 storage 类(class)。

# settings.py

if DEBUG:
    DEFAULT_FILE_STORAGE = 'api.storage_backends.PublicMediaStorage'
else:
    DEFAULT_FILE_STORAGE = 'api.storage_backends.PrivateMediaStorage'


# models.py
class Foo(models.Model):
    file = models.FileField() # without storage

在文件上传过程中,Django 会调用 DEFAULT_FILE_STORAGE懒惰 时尚。

笔记

这些设置不会使用 创建迁移文件storage 范围

更新-1

如果您想更好地控制存储,请创建自己的自定义文件字段并在模型中连接
def get_storage():
    """
    Change this function to whatever way as you need
    """
    from api.storage_backends import PublicMediaStorage, PrivateMediaStorage
    if DEBUG:
        return PublicMediaStorage()
    else:
        return PrivateMediaStorage()


class CustomFileField(models.FileField):
    def __init__(self, *args, **kwargs):
        kwargs['storage'] = get_storage() # calling external function
        super().__init__(*args, **kwargs)


class Foo(models.Model):
    file = CustomFileField() # use custom filefield here

关于python - Django 仅在生产环境中使用私有(private) S3 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437637/

相关文章:

python - 如何在 GET 或 POST 中多次使用 Django 表单字段

amazon-s3 - React Router + AWS 后端,如何做 SEO

python - 除 Sieve 之外的快速素数生成器

python - "Internal Server Error"与 Hello World Python 应用程序

python - 为什么此 Popen 调用在 Django 2.0 中返回 "io.UnsupportedOperation: fileno"错误?

python - Google AppEngine 使用哪个 simplejson 模块?

amazon-web-services - 跳过 S3 生命周期策略中的某些文件夹

ClickOnce 和 Amazon S3

python - 为什么将过程放入函数中会快得多?

python - 为什么一个简单的 2 层神经网络无法学习 0,0 序列?