Enable the gridfs connection for user authentication. Before executing the script, you can
From pymongo import Connection
From gridfs import *
Con = Connection ("mongodb: // admin: admin@127.0.0.1: 27017") # Use URI to create a database link, of course, there are other ways to authorize, it is the administrator account of mongodb, and the general account does not know why it is not,
Db = con ['repository'] # connect to a specific database
Fs = gridfs. GridFS (db, 'images') # connect to the collection. If it does not exist, it will be created.
Fs.put('data.txt ')
ObjectId ('50b8176989ee3209bccb0b54') # The shell returns the id of the file in mongodb. At this time, two sets are created in the database, images. chunk and images. files.
About how to import ObjectId
In pymongo 2.2, You need to import data from pymongo. objectid.
Import from bson. objectid in version 2.2 and later
The Python script is as follows:
_ Author _ = 'jiang't'
# Encoding = UTF-8
From pymongo import Connection
From gridfs import *
From PIL import Image
From bson. objectid import ObjectId
Import StringIO
Import threading, time
# File Processing System
Class GFS:
# Define 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") # create a mongodb Connection
GFS. db = GFS. c ['maidiansha'] # connect to the specified database
GFS. fs = GridFS (GFS. db, collection = 'images') # connect to a specific collection
# Initialization
Def _ init _ (self ):
Print "_ init __"
GFS. _ connect ()
Print "server info" + "*" * 40
Print GFS. c. server_info
# Obtain a single column object
@ Staticmethod
Def getInstance ():
GFS. locker. acquire ()
Try:
GFS. instance
If not GFS. instance:
GFS. instance = GFS ()
Return GFS. instance
Finally:
GFS. locker. release ()
# Write
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)
Failed t Exception as e:
Print "Exception ==>>% s" % e
Finally:
GFS. c = None
GFS. _ connect ()
Return gf
# Retrieving images
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 t Exception, e:
Print e
Return (None, None)
Finally:
If gf:
Gf. close ()
# Write image files in gridFS to the hard disk
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! "
# Getting the file list
Def list (self ):
Return GFS. fs. list ()
# Deleting an object
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)