2017-08-10 6 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' 

を行:

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.

関連する問題