building web applications with mongo db: an update

It’s been a while since I did anything with MongoDB, a NoSQL (Not Only SQL) open source database. My MongoDB rad skills[1] had gotten a little rusty as a consequence. So I moseyed on over to the MongoDB download site, grabbed a zipped up Windows x86-64 copy, plopped it down on my machine, and then started to follow the directions to “Building Web Applications with MongoDB: An Introduction.”

It’s a great little presentation, but it has a few little quirks that this posting is meant to smooth over. They are:

  1. His presentation is on Mac OS X. This update is for Windows 8.1 Update 1 64-bit.
  2. This update contains the full source code to the three web application files, with a few minor corrections.
  3. This update contains a MongoDB console correction.

This update is preparation to get everything set up on Windows 8.1 before running the presentation. When you run the presentation it will go a lot smoother for you. And you should run the presentation to get the full benefits of learning about MongoDB. But first the software we’ll need to install:

Software Version
Python 2.7.8
pymongo 2.7.2
bottle 0.12.7
MongoDB 2.6.4

Please note that these are the versions as of the time this post was published. If you come across this post at some point in the future, they may be different (i.e. higher).

First let’s install Python and the infrastructure tools for the MongoDB Python driver and web infrastructure you’ll need to run the presentation.

  1. Pick up the Python software from ActiveState’s ActivePython download page. Make sure to select a version 2.7 Python. Pick the 64-bit MSI installer, run the installer, and take the defaults. It will put all the binaries and tools into C:\Python27.
  2. After the Python installation open a command shell and cd into C:\Python27\Scripts. There you’ll find easy_install.exe and pip.exe. You can use either tool to install pymongo and bottle, but it’s easier to use easy_install. For pymongo type “easy_install pymongo” followed by “easy_install bottle”.

Next download the MongoDB database software from the MongoDB download page. Select the 64-bit zip file. What follows is how I have my sandbox set up for this. You can change it to suit your environment if you want.

  1. Create a local sandbox area. Mine is C:\Java (an historical artifact).
  2. Unzip the MongoDB zip file into C:\Java. My unzipped MongoDB application is located in C:\Java\mongodb-win32-x86_64-2008plus-2.6.4
  3. Create a directory structure for the MongoDB data store. Mine is C:\Java\data\db
  4. In the C:\Java\mongodb-win32-x86_64-2008plus-2.6.4\bin folder create a batch file called runmongo.bat
  5. In that batch file put the single line ‘mongod –dbpath C:/Java/data/db’. Now you can double click it in the file explorer and start up MongoDB pointing to where it should place all its data files.

Finally create a sub work folder to hold the application file. Mine is C:\Java\MongoDB. Place the following three files into that location. I use the MongoDB subfolder just to keep things straight, but you could call it Fred and it would still work. What follows are the three files to copy:

import bottle
import pymongo
import guestbookDAO

#This is the default route, our index page. Here we need to read the documents from MongoDB.
@bottle.route('/')
def guestbook_index():
    mynames_list = guestbook.find_names()
    return bottle.template('index', dict(mynames = mynames_list))

#We will post new entries to this route so we can insert them into MongoDB
@bottle.route('/newguest', method='POST')
def insert_newguest():
    name = bottle.request.forms.get("name")
    email = bottle.request.forms.get("email")
    guestbook.insert_name(name, email)
    bottle.redirect('/')

#This is to set up the connection.

#First, set up a connection string. My server is running on this computer, so localhost is OK.
connection_string = "mongodb://localhost"
#Next, let PyMongo know about the MongoDB connection we want to use. PyMongo will manage the connection pool.
connection = pymongo.MongoClient(connection_string)
#Now we want to set a context to the names database we created using the Mongo interactive shell.
database = connection.names
#Finally let our data access object class we built, which acts as our data layer, know about this.
guestbook = guestbookDAO.GuestbookDAO(database)

bottle.debug(True)
bottle.run(host='localhost', port=8082)

File: index.py

 

import string

class GuestbookDAO(object):

#Initialize our DAO class with the database and set the MongoDB collection we want to use.
    def __init__(self, database):
        self.db = database
        self.mynames = database.mynames

    def find_names(self):
        l = []
        for each_name in self.mynames.find():
            l.append({'name':each_name['name'], 'email':each_name['email']})

        return l

    def insert_name(self, newname, newemail):
        newdoc = {'name':newname, 'email':newemail}
        self.mynames.insert(newdoc)

File: guestbookDAO.py

 

<!DOCTYPE html>
<html>
    <head>
        <title>Welcome to MongoDB!</title>
        <style type="text/css">
            body { font-family: sans-serif; color: #4f494f; }
            form input { border-radius: 7.5px; }
            h5 { display: inline; }
            .label { text-align: right; }
            .guestbook { float: left; padding-top: 10px; }
            .name { width: 100%; float: left; padding: 3px; }
            .wrapper { padding-left: 25px; padding-top: 20px; }
        </style>
    </head>

    <body>
        <div class="wrapper">
            <h1>Welcome To MongoDB</h1>
            <div class="guestbook_input">
                <form method="post" class="form" action="/newguest">
                    Name: <input type="text" name="name"/>
                    Email: <input type="text" name="email"/>
                    <input type="submit" value="Add Guest"/>
                </form>
            </div>
            <div class="guestbook">
                <h3>Guests:</h3>
                %for name in mynames:
                <div class="name">
                <h5>Name:</h5> {{name['name']}},
                <h5>Email:</h5> {{name['email']}}
                </div>
                %end
            </div>
        </div>
    </body>
</html>

File: index.html

 

Copy these three files into C:\Java\MongoDB.

Go to the MongoDB presentation and follow along. When it comes time to start MongoDB double click the startmongo.bat file in the file explorer. When it comes time to start the MongoDB shell, double click mongo.exe. When it comes time to run the web application in C:\Java\MongoDB (comprised of those three files you should have copied there) open a command prompt, cd to C:\Java\MongoDB, and type ‘python index.py’ and hit return. Then follow the rest of the demo.

Note that when the demo talks about deleting records in your web application’s database, you should type ‘db.mynames.remove({})’ instead of ‘db.mynames.remove()’. MongoDB has advanced enough from the version used in the demo to cause some minor annoyance if you follow the speaker’s directions exactly.

[1] I guess I’m an old fart; I refuse to spell the plural of skills with a ‘z’.


One comment


Comments are closed.