Database Reference
In-Depth Information
Begin by firing up Python:
Python 2.6.6 (r266:84292, Oct 12 2012, 14:23:48)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.>>>
The standard driver for Python is called PyMongo, and it was written by Mike Dirolf.
Because the PyMongo driver is supported directly by MongoDB, Inc., the company
that publishes MongoDB, you can rest assured that it will be regularly updated and
maintained. So, let's go ahead and import the library. You should see something like
the following:
>>> from pymongo import Connection
>>> import gridfs
>>>
If PyMongo isn't installed correctly, you will get an error similar to this:
>>> import gridfs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named gridfs
>>>
If you see the latter message, chances are something was missed during installation.
In that case, pop back to Chapter 2 and follow the instructions to install PyMongo again.
Connecting to the Database
Before you can retrieve information from a database, you must first establish a connection
to it. When you were using the mongofiles utility earlier in this chapter, you probably
noticed the reference to 127.0.0.1 . This value is also known as the localhost , and it
represents your computer's loopback address. This value is simply a shortcut for telling a
computer to talk to itself. The reason mongofiles mentioned this IP address is that it was
actually connecting to MongoDB through the network. The default is to connect to the
local machine on the default MongoDB port. Because you haven't changed the default
settings, mongofiles can find and connect to your database without any trouble.
When using MongoDB with Python, however, you need to connect to the database
and then set up GridFS. Fortunately, this is easy to do:
>>> db = Connection().test
>>> fs = gridfs.GridFS(db)
>>>
The first line opens the connection and selects the database. By default, mongofiles
uses the test database; hence, you'll find your dictionary file in test . The second line
sets up GridFS and prepares it for use.
 
Search WWH ::




Custom Search