【问题标题】:Unable to read Django FieldFile in custom storage`无法读取自定义存储中的 Django FieldFile`
【发布时间】:2017-08-10 01:36:00
【问题描述】:

我正在尝试为我的 Django 应用创建一个 custom file storage class,它透明地记录所有保存文件的哈希值。

我的测试存储类非常简单:

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 存储类中访问原始文件内容的正确方法是什么?

【问题讨论】:

    标签: python django django-storage


    【解决方案1】:
    raw_content = content.open().read()
    

    改成

    raw_content = content.read()
    

    我认为您可以查看这些手册。

    Django Manual _save

    _save(name, content)¶ 由 Storage.save() 调用。该名称将已经通过 get_valid_name() 和 get_available_name(),并且 content 本身就是一个 File 对象。

    所以内容是文件对象。

    Django Manual FieldFile.open

    打开或重新打开与此实例关联的文件 指定模式。与标准 Python open() 方法不同,它没有 返回一个文件描述符。

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      相关资源
      最近更新 更多