[Python] Python + mongodb +GridFS 实现图片的存取 →→→→→进入此内容的聊天室

来自 , 2021-01-04, 写在 Python, 查看 255 次.
URL http://www.code666.cn/view/9ceee750
  1. __author__ = 'jiangyt'
  2. #encoding=utf-8
  3. from pymongo import Connection
  4. from gridfs import *
  5. from PIL import Image
  6. from bson.objectid import ObjectId
  7. import StringIO
  8. import threading, time
  9.  
  10. #文件处理系统
  11. class GFS:
  12. #定义connection and fs
  13.     c = None
  14.     db = None
  15.     fs = None
  16.     instance = None
  17.     locker = threading.Lock()
  18.  
  19.     @staticmethod
  20.     def _connect():
  21.         if  not GFS.c:
  22.    GFS.c = Connection( "mongodb://admin:admin@127.0.0.1:27017") # 建立mongodb的连接
  23.             GFS.db = GFS.c['maidiansha']  #连接到指定的数据库中
  24.    GFS.fs = GridFS(GFS.db,  collection='images') #连接到具体的collection中
  25.  
  26.  
  27.     #初始化
  28.     def __init__(self):
  29.         print "__init__"
  30.         GFS._connect()
  31.         print "server info " + " * " * 40
  32.         print GFS.c.server_info
  33.  
  34.  
  35.     #获得单列对象
  36.     @staticmethod
  37.     def getInstance():
  38.         GFS.locker.acquire()
  39.         try:
  40.             GFS.instance
  41.             if not GFS.instance:
  42.                 GFS.instance = GFS()
  43.             return GFS.instance
  44.         finally:
  45.             GFS.locker.release()
  46.  
  47.  
  48.     #写入
  49.     def put(self, name,  format="png",mime="image"):
  50.         gf = None
  51.         data = None
  52.         try:
  53.             data = StringIO.StringIO()
  54.             name = "%s.%s" % (name,format)
  55.    image = Image.open(name)
  56.             image.save(data,format)
  57.             #print "name is %s=======data is %s" % (name, data.getvalue())
  58.    gf = GFS.fs.put(data.getvalue(), filename=name, format=format)
  59. except Exception as e:
  60.    print "Exception ==>> %s " % e
  61.         finally:
  62.             GFS.c = None
  63.             GFS._connect()
  64.  
  65.  
  66.             return gf
  67.  
  68.  
  69.     #获得图片
  70.     def get(self,id):
  71.         gf = None
  72.         try:
  73.             gf  = GFS.fs.get(ObjectId(id))
  74.             im = gf.read()                  #read the data in the GridFS
  75.             dic = {}
  76.             dic["chunk_size"] =  gf.chunk_size
  77.             dic["metadata"] = gf.metadata
  78.             dic["length"] = gf.length
  79.             dic["upload_date"] = gf.upload_date
  80.             dic["name"] = gf.name
  81.             dic["content_type"] = gf.content_type
  82.    dic["format"] = gf.format
  83.             return (im , dic)
  84.         except Exception,e:
  85.             print e
  86.             return (None,None)
  87.         finally:
  88.             if gf:
  89.                 gf.close()
  90.  
  91.  
  92.     #将gridFS中的图片文件写入硬盘
  93.     def write_2_disk(self, data, dic):
  94.         name = "./get_%s" % dic['name']
  95. if name:
  96.             output = open(name, 'wb')
  97.    output.write(data)
  98.    output.close()
  99.    print "fetch image ok!"
  100.  
  101.     #获得文件列表
  102.     def list(self):
  103.         return GFS.fs.list()
  104.  
  105.  
  106.     #删除文件
  107.     def remove(self,name):
  108.         GFS.fs.remove(name)
  109.  
  110. if __name__== '__main__':
  111. image_name= raw_input("input the image name>>")
  112. if image_name:
  113.            gfs = GFS.getInstance()
  114.            if gfs:
  115.                 image_id = gfs.put(image_name)
  116.                 print "==========Object id is %s  and it's type is %s==========" % (image_id , type(image_id))
  117. (data, dic) = gfs.get(ObjectId(image_id))
  118. gfs.write_2_disk(data, dic)
  119. #//python/5817

回复 "Python + mongodb +GridFS 实现图片的存取"

这儿你可以回复上面这条便签

captcha