欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 2.6.2 + mongodb 2.0.7 +GridFS 实现图片的存取

程序员文章站 2023-11-11 19:48:46
开启用户验证下的gridfs 连接使用,在执行脚本前可以在python shell中 from pymongo import connection from gridfs im...

开启用户验证下的gridfs 连接使用,在执行脚本前可以在python shell中

from pymongo import connection
from gridfs import *

con = connection("mongodb://admin:admin@127.0.0.1:27017")#用uri的方式建立的链接,当然也有其他的方式进行授权,现在是mongodb的管理员帐号,普通帐号不知道为什么不可以,
db = con['repository']#连接到具体的数据库
fs = gridfs.gridfs(db, 'images')#连接到collection,不存在的话会进行创建
fs.put('data.txt')
objectid('50b8176989ee3209bccb0b54')#shell 返回文件在mongodb中的id,此时该数据库中会新建两个集合,images.chunk 和images.files

其中关于objectid的导入问题
在pymongo 2.2版本一下需要从pymongo.objectid中导入
在2.2及以上版本中从bson.objectid 中导入

python 脚本如下
__author__ = 'jiangyt'
#encoding=utf-8
from pymongo import connection
from gridfs import *
from pil import image
from bson.objectid import objectid
import stringio
import threading, time

#文件处理
class gfs:
#定义connection and fs
    c = none
    db = none
    fs = none
    instance = none
    locker = threading.lock()

    @staticmethod
    def _connect():
        if  not gfs.c:
   gfs.c = connection( "mongodb://admin:admin@127.0.0.1:27017") # 建立mongodb的连接
            gfs.db = gfs.c['maidiansha']  #连接到指定的数据库中
   gfs.fs = gridfs(gfs.db,  collection='images') #连接到具体的collection中


    #初始化
    def __init__(self):
        print "__init__"
        gfs._connect()
        print "server info " + " * " * 40
        print gfs.c.server_info


    #获得单列对象
    @staticmethod
    def getinstance():
        gfs.locker.acquire()
        try:
            gfs.instance
            if not gfs.instance:
                gfs.instance = gfs()
            return gfs.instance
        finally:
            gfs.locker.release()


    #写入
    def put(self, name,  format="png",mime="image"):
        gf = none
        data = none
        try:
            data = stringio.stringio()
            name = "%s.%s" % (name,format)
   image = image.open(name)
            image.save(data,format)
            #print "name is %s=======data is %s" % (name, data.getvalue())
   gf = gfs.fs.put(data.getvalue(), filename=name, format=format)
except exception as e:
   print "exception ==>> %s " % e
        finally:
            gfs.c = none
            gfs._connect()


            return gf


    #获得图片
    def get(self,id):
        gf = none
        try:
            gf  = gfs.fs.get(objectid(id))
            im = gf.read()                  #read the data in the gridfs
            dic = {}
            dic["chunk_size"] =  gf.chunk_size
            dic["metadata"] = gf.metadata
            dic["length"] = gf.length
            dic["upload_date"] = gf.upload_date
            dic["name"] = gf.name
            dic["content_type"] = gf.content_type
   dic["format"] = gf.format
            return (im , dic)
        except exception,e:
            print e
            return (none,none)
        finally:
            if gf:
                gf.close()


    #将gridfs中的图片文件写入硬盘
    def write_2_disk(self, data, dic):
        name = "./get_%s" % dic['name']
if name:
            output = open(name, 'wb')
   output.write(data)
   output.close()
   print "fetch image ok!"

    #获得文件列表
    def list(self):
        return gfs.fs.list()


    #删除文件
    def remove(self,name):
        gfs.fs.remove(name)

if __name__== '__main__':
image_name= raw_input("input the image name>>")
if image_name:  www.2cto.com
           gfs = gfs.getinstance()
           if gfs:
                image_id = gfs.put(image_name)
                print "==========object id is %s  and it's type is %s==========" % (image_id , type(image_id))
(data, dic) = gfs.get(objectid(image_id))
gfs.write_2_disk(data, dic)