Write a picture file in Gridfs to the hard disk

Source: Internet
Author: User

Enable the GRIDFS connection under user authentication, which can be used in Python shell before executing the script

From Pymongo import Connection
From GRIDFS Import *
con = Connection ("Mongodb://admin:[email protected]:27017") #用URI的方式建立数据库的链接, of course there are other ways to authorize it, now is the administrator account of MongoDB, General account do not know why not to,
db = Con[' repository '] #连接到具体的数据库
FS = Gridfs. GRIDFS (db, ' images ') #连接到collection, will be created if not present
Fs.put (' Data.txt ')
ObjectId (' 50b8176989ee3209bccb0b542881064151 ') #shell returns the ID of the file in MongoDB, at which time a new two collection is created in the database, Images.chunk and Images.files
One of the issues about Objectid import
In the Pymongo 2.2 version you need to import from Pymongo.objectid
Import from Bson.objectid in version 2.2 and above
The Python script is as follows
__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:[email protected]:27017") # Establishing a MongoDB connection
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.codesec.net
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)

Write a picture file in Gridfs to the hard disk

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.