
Django4.0 管理文件-文件存储
在后台,Django将如何以及在哪里存储文件的决策委托给文件存储系统。这个对象实际上理解文件系统、打开和读取文件等。
Django 的默认文件存储通过 DEFAULT_FILE_STORAGE
配置;如果你不显式地提供存储系统,这里会使用默认配置。
存储对象
虽然大部分时间你可以使用 File 对象(将该文件委托给合适的存储),但你可以直接使用文件存储系统。你可以创建一些自定义文件存储类的示例,或使用通常更有用的全局默认存储系统:
>>> from django.core.files.base import ContentFile >>> from django.core.files.storage import default_storage >>> path = default_storage.save('path/to/file', ContentFile(b'new content')) >>> path 'path/to/file' >>> default_storage.size(path) 11 >>> default_storage.open(path).read() b'new content' >>> default_storage.delete(path) >>> default_storage.exists(path) False
内置文件存储类
Django 附带一个 django.core.files.storage.FileSystemStorage
类,这个类实现基础的本地文件系统文件存储。
例如,下面的代码将存储上传文件到 /media/photos
而会忽略你在 MEDIA_ROOT
的设置:
from django.core.files.storage import FileSystemStorage from django.db import models fs = FileSystemStorage(location='/media/photos') class Car(models.Model): ... photo = models.ImageField(storage=fs)
自定义存储系统( Custom storage systems )的工作方式也一样:将它们作为 storage
参数传递给 FileField
。
使用callable
你可以使用callable作为 FileField
或 ImageField
的 storage
参数。它允许你在运行时修改存储参数,不同环境选择不同存储,例如。
当模型类被加载时,callable将进行判断,并返回 Storage
实例。
例如:
from django.conf import settings from django.db import models from .storages import MyLocalStorage, MyRemoteStorage def select_storage(): return MyLocalStorage() if settings.DEBUG else MyRemoteStorage() class MyModel(models.Model): my_file = models.FileField(storage=select_storage)