2017-08-10 56 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.