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()
self.db=self.conn['library']
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()
self.write(str(list(articleList)))
else:
article = str(self.db.articles.find_one({"id":articleid}))
self.write(article)
def delete(self):
self.db.articles.drop()
application = tornado.web.Application([
(r"/articles", Article),
],debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

view raw

tornadomongo.py

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("http://127.0.0.1:8888/articles", "POST", body=body)
data = {'id':'2', 'author':'A', 'genre':'tragedy'}
body = urlencode(data)
h.request("http://127.0.0.1:8888/articles", "POST", body=body)
## View all articles
content, response = h.request("http://127.0.0.1:8888/articles", "GET")
print response
## View articles
data = {"articleid":1}
data = urlencode(data)
content, response = h.request("http://127.0.0.1:8888/articles"+ "?" + data, "GET")
print response
## Delete articles
content, response = h.request("http://127.0.0.1:8888/articles", "DELETE")
content, response = h.request("http://127.0.0.1:8888/articles", "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

Output

{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.