我正在做一个pymongo连接程序,它使用python在mongodb上创建一个gridfs数据库,并在数据库中添加一个图像。我使用命令行解析器调用这些方法。我已经成功地在数据库中添加了图像,它也反映在mongodb数据库中,但是当我调用show函数时,它显示image not found。 代码如下:
import argparse
from PIL import Image
from pymongo import Connection
import gridfs
from bson.binary import Binary
# setup mongo
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
# connect to the database & get a gridfs handle
mongo_con = Connection(MONGODB_HOST, MONGODB_PORT)
fs = gridfs.GridFS(mongo_con.ank1)
def add_image():
"""add an image to mongo's gridfs"""
gridfs_filename = 'ofc2.jpg'
fileID = fs.put(open('C:\Python27\ofc2.jpg','r'),filename='ofc2.jpg')
print "created new gridfs file {0} with id {1}".format(gridfs_filename, fileID)
def show():
"""start the flask service"""
filename='ofc2.jpg'
if not fs.exists(filename="ofc2.jpg"):
raise Exception("mongo file does not exist! {0}".format(filename))
im_stream = fs.get_last_version(filename)
im = Image.open(im_stream)
im.show()
def main():
# CLI
parser = argparse.ArgumentParser()
parser.add_argument('--show', action='store_true', help='start the service')
parser.add_argument('--add', action='store_true', help='add an image via URL')
args = parser.parse_args()
if args.show:
show()
elif args.add:
add_image()
main()
以下是操作:
^{pr2}$在mongodb上
mongodb输出
MongoDB Enterprise > show dbs;
ank 0.000GB
ank1 0.000GB
ankit 0.000GB
gridfs_example 0.000GB
local 0.000GB
MongoDB Enterprise > use ank1
switched to db ank1
MongoDB Enterprise > show collections
fs.chunks
fs.files
MongoDB Enterprise > db.fs.files.find().pretty()
{
"_id" : ObjectId("5802397f0f84ea122c6176a6"),
"chunkSize" : 261120,
"filename" : "ofc2.jpg",
"length" : 335,
"uploadDate" : ISODate("2016-10-15T14:13:19.882Z"),
"md5" : "ef937ff6e6a00e64a2dda34251ca03b5"
}
我不知道问题是什么我在fedora做了同样的程序有效。但是在windows的im中,这个问题是与os或python版本有关的吗
您可能需要使用BytesIO类将
im_stream
转换为用于读取的字节。在相关问题 更多 >
编程相关推荐