使用带有python的gridfs将jpg图像保存到mongodb,并在需要时从数据库中检索

时间:2015-06-08 15:02:36

标签: python mongodb gridfs

我正在尝试使用带有python的gridfs将jpg图像保存到mongodb,并在需要时从数据库中检索它。看起来它保存得很好,然后我将其fileid存储在集合中,在阅读时我用它来定位图像。但它并没有让我恢复以前保存的图像。

这是类定义:

class dbase():
    database=""

def __init__(self,dbserver,dbport ):
    from pymongo import MongoClient

    client =MongoClient()
    self.database = client['test']

def Savetodb(self,event):
    import gridfs
    import tkMessageBox
    result = tkMessageBox.askokcancel("Save to db???", "Confirm Save")
    if result:
    # get image name and image file from the widget box
        filename=event.widget.cget("text")
        img =event.widget.cget("image")
        fs = gridfs.GridFS(self.database)
        fileid = fs.put(img,filename=filename)
        self.database.my_collection.insert_one({"imagefile":filename,"fileid":fileid})


def Getfromdb(self,outfilename):
    import gridfs
    fs = gridfs.GridFS(self.database)
    fid = ""

    for item in self.database.my_collection.find({"imagefile":outfilename}):
        fid=item["fileid"]
    if fid <> "":
        outputdata = fs.get(fid).read()
        return outputdata

0 个答案:

没有答案