首页 > 解决方案 > Mongodb GridFS读取返回空内容

问题描述

当我使用 mongodb 的 python api mongoengine 从 GridFS 读取文件时,第一次读取后我得到了空内容。这是我尝试过的:

class Test(Document):
    file=FileField()
a = Test(id=id)
print a.file.read() # has expected output
print a.file.read() # empty
print a.file.read() # empty`

所以我很好奇 GridFS 读取是如何工作的,提前感谢任何提示:)

标签: mongodbgridfs

解决方案


我们将不得不改进相应的文档,因为它是一个常见的混淆来源,但是一旦你阅读了它,你需要“倒带”它。

IE:

class Test(Document):
    file = FileField()

a = Test(id=id)
print a.file.read() # has expected output

a.file.seek(0)

print a.file.read()

请注意,这并非特定于 MongoEngine,而是底层 GridFS/GridOut 类文件对象的行为方式


推荐阅读