Tornado – MongoDB

Yes, Tornado gells well with many databases like mysql, sqlite and mongodb. Below is an example of database connectivity and interaction with MongoDB from Tornado.

In this example, the user or client connects MongoDB database : library and collection: articles )with HTTP requests.

  • get() – displays the records of mongodb collection with article id
  • post() – helps the client to add articles with id, article title, and genre
  • delete() – deletes the articles’s information

Please note: the example assumes that mongo server and pymongo (python driver for mongodb) is installed on the system

import tornado.ioloop
import tornado.web
import urlparse
## mongodb and pymongo installation assumed
import pymongo
from pymongo import Connection
class Article(tornado.web.RequestHandler):
def initialize(self):
self.conn = pymongo.Connection()
def post(self):
article = urlparse.parse_qs(self.request.body)
for key in article:
article[key] = article[key][0]
collection = self.db['articles']
self.db.articles.insert({"id":article['id'], "author":article['author'], "genre":article['genre']})
def get(self):
articleid = self.get_argument("articleid", None)
if articleid is None:
articleList = self.db.articles.find()
article = str(self.db.articles.find_one({"id":articleid}))
def delete(self):
application = tornado.web.Application([
(r"/articles", Article),
if __name__ == "__main__":

view raw

hosted with ❤ by GitHub

Client Request

import httplib2
from urllib import urlencode
h = httplib2.Http()
## Add articles
data = {'id':'1', 'author':'B', 'genre':'comedy'}
body = urlencode(data)
h.request("", "POST", body=body)
data = {'id':'2', 'author':'A', 'genre':'tragedy'}
body = urlencode(data)
h.request("", "POST", body=body)
## View all articles
content, response = h.request("", "GET")
print response
## View articles
data = {"articleid":1}
data = urlencode(data)
content, response = h.request(""+ "?" + data, "GET")
print response
## Delete articles
content, response = h.request("", "DELETE")
content, response = h.request("", "GET")
print response

The client program:

  • Adds two records to the articles collection with HTTP POST request
  • It then reads one of the articles with the HTTP GET request with article 1
  • Client then drops all the records of the collection with HTTP DELETE request


{u'genre': u'comedy', u'_id': ObjectId('503f4a601d41c81bf9d3360d'), u'id': u'1', u'author': u'B'}
No Articles found

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.