2017-08-10 36 views
0

我試圖爲我的Django應用程序製作custom file storage class,該應用程序透明地記錄了保存的所有文件的哈希值。無法讀取自定義存儲中的Django FieldFile

我的測試存儲類是相當簡單:

from django.core.files.storage import Storage 
from django.db.models.fields.files import FieldFile 

from utils import get_text_hash 

class MyStorage(Storage) 

    def _save(self, name, content): 
     if isinstance(content, FieldFile): 
      raw_content = content.open().read() 
     else: 
      raw_content = content 
     assert isinstance(raw_content, basestring) 
     print(get_text_hash(raw_content)) 
     return super(MyStorage, self)._save(name, content) 

然而,當我試着將文件保存在我的應用程序,我得到的錯誤:

'NoneType' object has no attribute 'read' 

與上回溯結束line:

raw_content = content.open().read() 

爲什麼open()返回None而不是文件句柄?在Django存儲類中訪問原始文件內容的正確方法是什麼?

回答

0
raw_content = content.open().read() 

變化

raw_content = content.read() 

我想你可以檢查這些手冊。

Django Manual _save

_save(name, content)¶ Called by Storage.save(). The name will already have gone through get_valid_name() and get_available_name(), and the content will be a File object itself.

所以內容是File對象。

Django Manual FieldFile.open

Opens or reopens the file associated with this instance in the specified mode. Unlike the standard Python open() method, it doesn’t return a file descriptor.