mongodb操作文件
mongodb操作文件,主要是通过GridFS类。存储文件主要存放在fs中,其中的fs是数据库默认的。并且GridFS是直接与数据库打交道,与collection集合无关。
===============
https://docs.mongodb.com/manual/core/gridfs/
When to Use GridFS
In MongoDB, use GridFS for storing files larger than 16 MB.
=======================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | '' ' Created on 2013-8-6 class mongoInsert @author: tree '' ' __metaclass__ = type import os from pymongo.database import Database import time import gridfs class mongoImg( object ): "" "mongoInsert is a class for inserting document "" " def __init__(self, database, dir): "" "Create a new instance of : class :mongoInsert :Parameters: - `database`: database to use - `dir` : directory of document "" " if not isinstance(database, Database): raise TypeError( "database must be an instance of Database" ) if len(dir) < 1: raise TypeError( "dir must be an string of directory" ) # self.__con = Connection() self.__imgdb = database self.__imgfs = gridfs.GridFS (self.__imgdb) self.__dir = dir self.__filelist=[] #save filepath in list.txt def __dirwalk(self,topdown=True): "" "traverse the documents of self.__dir and save in self.__filelist "" " sum=0 self.__filelist.clear() for root,dirs,files in os.walk(self.__dir,topdown): for name in files: sum+=1 temp=os.path. join (root,name) self.__filelist.append(temp) print(sum) #insert image def insert(self): "" "insert images in mongodb "" " self.__dirwalk() tStart = time.time() for fi in self.__filelist: with open (fi, 'rb' ) as myimage: data=myimage.read() self.__imgfs.put(data, content_type = "jpg" , filename =fi) tEnd =time.time () print ( "It cost %f sec" % (tEnd - tStart)) #get image by filename def getbyname(self,filename,savepath): "" " get img from mongdb by filename "" " if len(savepath) < 1: raise TypeError( "dir must be an string of directory" ) dataout=self.__imgfs.get_version(filename) try : imgout=open(savepath, 'wb' ) data=dataout.read() imgout.write(data) finally : imgout.close() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)