Sunday, January 11, 2015

How to retrieve data from MongoDB and display via web applications using Python Bottle Framework

First start the Mongo server using mongod command. In this example the following document data base has been used.

Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.

  • Routing: Requests to function-call mapping with support for clean and dynamic URLs.
  • Templates: Fast and pythonic built-in template engine and support for makojinja2and cheetah templates.
  • Utilities: Convenient access to form data, file uploads, cookies, headers and other HTTP-related metadata.
  • Server: Built-in HTTP development server and support for pastefapws3bjoern,gaecherrypy or any other WSGI capable HTTP server.
Run this Code and run the web browser http://localhost:8080/
************************************************************
Code:
************************************************************
import bottle
import pymongo


@bottle.route('/')
def home_page():


   #connect to mongodb
   connection = pymongo.MongoClient('localhost', 27017)
   #connect to mydb database
   db = connection.mydb
   #handle to friends Collection
   data = db.friends
   #getting all the document from friends
   friendsList = data.find()
   #construct string variable with friends names
   myfriendnames = ""
   for item in friendsList:
       myfriendnames = myfriendnames + ", " + item["name"]


   return myfriendnames


bottle.debug(True)

bottle.run(host='localhost', port=8080)

Cheers!
Uma

1 comment: