掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
在后臺(tái),Django將如何以及在哪里存儲(chǔ)文件的決策委托給文件存儲(chǔ)系統(tǒng)。這個(gè)對(duì)象實(shí)際上理解文件系統(tǒng)、打開和讀取文件等。

Django 的默認(rèn)文件存儲(chǔ)通過(guò) ?DEFAULT_FILE_STORAGE?配置;如果你不顯式地提供存儲(chǔ)系統(tǒng),這里會(huì)使用默認(rèn)配置。
雖然大部分時(shí)間你可以使用 File 對(duì)象(將該文件委托給合適的存儲(chǔ)),但你可以直接使用文件存儲(chǔ)系統(tǒng)。你可以創(chuàng)建一些自定義文件存儲(chǔ)類的示例,或使用通常更有用的全局默認(rèn)存儲(chǔ)系統(tǒng):
>>> 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)
FalseDjango 附帶一個(gè) ?django.core.files.storage.FileSystemStorage? 類,這個(gè)類實(shí)現(xiàn)基礎(chǔ)的本地文件系統(tǒng)文件存儲(chǔ)。
例如,下面的代碼將存儲(chǔ)上傳文件到 ?/media/photos? 而會(huì)忽略你在 ?MEDIA_ROOT?的設(shè)置:
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)自定義存儲(chǔ)系統(tǒng)( Custom storage systems )的工作方式也一樣:將它們作為 ?storage?參數(shù)傳遞給 ?FileField?。
你可以使用callable作為 ?FileField?或 ?ImageField?的 ?storage?參數(shù)。它允許你在運(yùn)行時(shí)修改存儲(chǔ)參數(shù),不同環(huán)境選擇不同存儲(chǔ),例如。
當(dāng)模型類被加載時(shí),callable將進(jìn)行判斷,并返回 ?Storage?實(shí)例。
例如:
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) 
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流