Directly paste the English text. Poor translation affects readers. The English text is as follows:
Gridfs example
This example shows how to use
GridfsTo store large binaryobjects (e.g. Files) in MongoDB.
See also
The API docs
Gridfs.
See also
This blog postfor some motivation behind this API.
Setup
We start by creating
GridfsInstance to use:
>>> from pymongo import Connection>>> import gridfs>>>>>> db = Connection().gridfs_example>>> fs = gridfs.GridFS(db)
Every
GridfsInstance is created with and willoperate on a specific
DatabaseInstance.
Saving and retrieving data
The simplest way to work
GridfsIs to use its key/valueinterface (
Put ()AndGet ()
Methods). To write data to gridfs, usePut ():
>>> a = fs.put("hello world")
Put ()Creates a new file in gridfs,
And returnsthe value of the file document's"_ Id"Key. Given that
"_ Id"We can use
Get ()To get back the contents of thefile:
>>> fs.get(a).read()'hello world'
Get ()Returns a file-like object,
So we get thefile's contents by calling
Read ().
In addition to puttingStrAs a gridfs file, we can alsoput any file-like object (an object with
Read ()Method). gridfs will handle reading the file in chunk-sized segmentsautomatically. We can also add additional attributes to the file askeyword arguments:
>>> b = fs.put(fs.get(a), filename="foo", bar="baz")>>> out = fs.get(b)>>> out.read()'hello world'>>> out.filenameu'foo'>>> out.baru'baz'>>> out.upload_datedatetime.datetime(...)
The attributes we set in
Put ()Are stored in thefile document, and retrievable after callingGet ().
Some attributes (like"FILENAME") Arespecial and are defined in the gridfs specification-see thatdocument for more details.
The example source code is as follows:
from pymongo import Connectionimport gridfsdb = Connection().gridfs_examplefs = gridfs.GridFS(db)a = fs.put("hello world")print acontent = fs.get(a).read()print contentb = fs.put(fs.get(a), filename="foo", bar="baz")out = fs.get(b)print bprint out.filenameprint out.bar