简体   繁体   English

无法在自定义存储中读取Django FieldFile`

[英]Unable to read Django FieldFile in custom storage`

I'm attempting to make a custom file storage class for my Django app that transparently logs a hash of all files saved. 我正在尝试为我的Django应用程序创建一个自定义文件存储类该类透明地记录所有已保存文件的哈希。

My test storage class is pretty trivial: 我的测试存储类非常简单:

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)

However, when I try and save a file in my app, I get the error: 但是,当我尝试在应用程序中保存文件时,出现错误消息:

'NoneType' object has no attribute 'read'

with the traceback ending on the line: 追溯在该行结束:

raw_content = content.open().read()

Why is open() returning None instead of a file handle? 为什么open()返回None而不是文件句柄? What's the proper way to access your raw file content inside a Django storage class? 在Django存储类中访问原始文件内容的正确方法是什么?

raw_content = content.open().read()

change to 改成

raw_content = content.read()

I think you can check these manuals. 我认为您可以查看这些手册。

Django Manual _save Django手册_save

_save(name, content)¶ Called by Storage.save(). _save(name,content)¶由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. 该名称将已经通过get_valid_name()和get_available_name()进行了命名,并且内容将是File对象本身。

So content is File object. 所以内容就是File对象。

Django Manual FieldFile.open Django手册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. 与标准的Python open()方法不同,它不返回文件描述符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM