Skip to main content
 首页 » 编程设计

python之带有 python 的 mongo gridfs

2025年05月04日9www_RR

我想直接从 python 脚本提供来自 gridfs 的图像,但我只看到空白屏幕:

#!/usr/bin/env python 
 
from pymongo import Connection 
import gridfs 
 
db = Connection().gridfs_example 
fs = gridfs.GridFS(db) 
 
f= fs.get_last_version('myimage') 
 
print "Content-type: %s \n\n " % f.content_type 
print "Content-Length: %d \n\n" % f.length 
print f.read() 

如果我将 f.read() 的输出写入文件,我就能看到“有效”图像 我可以通过以下方式从本地 FS 显示这张图片:

#!/usr/bin/env python 
 
img = open('image.jpg','rb').read() 
print "Content-type: image/jpeg" 
print "Content-Length: %d\n" % len(img) 
print img 

我做错了什么?

请您参考如下方法:

fs = gridfs.GridFS(db) 

是违规行。 GridFS 构造函数采用数据库实例,而不是连接对象。所以你必须做类似的事情:

conn = Connection() 
db = conn['mydb'] 
fs = gridfs.GridFS(db) 

希望这对您有所帮助!