0

我正在尝试使用 GridFS 获取存储在 mongoDB 中的文件。

我编写了这个函数来使用 GridFS 将文件存储到 mongoDB

def write_file_object(file_name):
with open(file_name) as mydoc:
    b = fs.put(mydoc, content_type="text/plain", filename="file")
    print b

这个函数通过传递文件 ID 来获取 mongoDB 中的文件,在这种情况下是 5590c2a71d41c81703458433。

def get_file_object(file_id):
out = fs.get(file_id).read()
print out   

但我不断收到此错误: gridfs.errors.NoFile: no file in gridfs collection Collection(Database(MongoClient('localhost', 27017), u'gridfs_example'), u'fs.files') with _id '5590c2a71d41c81703458433'

有帮助获取文件吗?我的方法错了吗?

4

1 回答 1

0

您需要将 id 字符串转换为ObjectId

from bson.objectid import ObjectId

def get_file_object(file_id):
  out = fs.get(ObjectId(file_id)).read()
  print out  
于 2015-06-29T07:39:42.690 回答