Python 操作GridFS


import pymongo
from pymongo import MongoClient
from gridfs import GridFS
class GFS(object):
    def __init__(self, file_db,file_table):
        self.file_db = file_db
        self.file_table = file_table
 
    def createDB(self): #連接數據庫,並創建文件數據庫與數據表
        client = MongoClient('localhost',27017)
        db = client[self.file_db]
        file_table = db[self.file_table]
        return (db,file_table)
 
    def insertFile(self,db,filePath,query): #將文件存入數據表
        fs = GridFS(db,self.file_table)
        if fs.exists(query):
            print('已經存在該文件')
        else:
            with open(filePath,'rb') as fileObj:
                data = fileObj.read()
                ObjectId = fs.put(data,filename = filePath.split('/')[-1])
                print(ObjectId)
                fileObj.close()
            return ObjectId
 
    def getID(self,db,query): #通過文件屬性獲取文件ID,ID為文件刪除、文件讀取做准備
        fs=GridFS(db, self.file_table)
        ObjectId=fs.find_one(query)._id
        return ObjectId
 
    def getFile(self,db,id): #獲取文件屬性,並讀出二進制數據至內存
        fs = GridFS(db, self.file_table)
        gf=fs.get(id)
        bdata=gf.read() #二進制數據
        attri={} #文件屬性信息
        attri['chunk_size']=gf.chunk_size
        attri['length']=gf.length
        attri["upload_date"] = gf.upload_date
        attri["filename"] = gf.filename
        attri['md5']=gf.md5
        print(attri)
        return (bdata, attri)
 
    # def listFile(self,db): #列出所有文件名
    #     fs = GridFS(db, self.file_table)
    #     gf = fs.list()
 
    # def findFile(self,db,file_table): #列出所有文件二進制數據
    #     fs = GridFS(db, table)
    #     for file in fs.find():
    #         bdata=file.read()
 
    def write_2_disk(self,bdata, attri): #將二進制數據存入磁盤
        name = "get_"+attri['filename']
        if name:
            output = open(name, 'wb')
        output.write(bdata)
        output.close()
        print("fetch image ok!")
 
    def remove(self,db,id): #文件數據庫中數據的刪除
        fs = GridFS(db, self.file_table)        
        fs.delete(id) #只能是id
 
 
if __name__=='__main__':
    gfs=GFS('fileDB','fileTable')
    (file_db,fileTable) = gfs.createDB() #創建數據庫與數據表
    filePath = 'C:/Users/Administrator/Desktop/02655.jpeg' #插入的文件
    query = {'filename': '02655.jpeg'}
    id=gfs.insertFile(file_db,filePath,query) #插入文件
    id=gfs.getID(file_db,query)
    (bdata,attri)=gfs.getFile(file_db,id) #查詢並獲取文件信息至內存
    gfs.write_2_disk(bdata,attri) #寫入磁盤
    # gfs.remove(file_db,id) #刪除數據庫中文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM