Database Reference
In-Depth Information
In this example, you use the put method to insert the file. It's important that you
capture the result from this method because it contains the document _id for your file.
PyMongo takes a different approach than mongofiles , which assumes the filename is
effectively the key (even though you can have duplicates). Instead, PyMongo references
files based on their _id . If you don't capture this information, then you won't be able to
reliably find the file again. Actually, that's not strictly true—you could search for a file
quite easily—but if you want to link this file to a particular user account, then you need
this _id .
Two useful arguments that can be used in conjunction with the put command
are filename and content_type . As you might expect, these arguments let you set the
filename and the content type of the file, respectively. This is useful for loading files
directly from disk. However, it is even handier when you're handling files that have been
received over the Internet or generated in memory because, in those cases, you can use
file-like semantics, but without actually having to create a real file on the disk.
Retrieving Files from GridFS
At long last, you're now ready to return your data! At this point, you have your unique _id ,
so finding the file is easy. The get method retrieves a file from GridFS:
>>> new_dictionary = fs.get(uid)
That's it! The preceding snippet returns a file-like object; thus, you can print all the
words in the dictionary using the following snippet:
>>> for word in new_dictionary:
... print word
Now watch in awe as a list of words quickly scrolls up the screen! Okay, so this isn't
exactly rocket science. However, the fact that it isn't rocket science or in any way difficult
is part of the beauty of GridFS—it does work as advertised, and it does so in an intuitive
and easily understood way!
Deleting Files
Deleting a file is also easy. All you have to do is call fs.delete() and pass the _id of the
file, as in the following example:
>>> fs.delete(uid)
>>> new_dictionary = fs.get(uid)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/pymongo-2.5.2-py2.6-linux-x86_64.
egg/gridfs/__init__.py", line 140, in get
 
Search WWH ::




Custom Search