web.py - a web framework on Python

09 May 2008

web.py is a web framework for python that is as simple and it is powerful too.Installation steps are given below , make sure your system is having Python's latest version and easyinstall (Easy Install is a python module (easyinstall) bundled with setup tools that lets you automatically download, build, install, and manage Python packages).

$sudo easyinstall easyinstall web.py

Or to install web.py, download and do python setup.py install.

Now the web.py is ready to use.Basically web.py is not following MVC architecture and here we use a code.py to write our classes and methods ,for rendering views we can use a templates folder.

Getting started with web.py

Create a file called code.py : where we writing our control methods

Create a directory for HTML file , lets say "templates" : where we creating the needed views for our methods

Now we have to import our web.py module , so add a line to our code.py

import web

web.py is imported to our application now.Now we need to tell web.py our URL structure.We can strt with a simple one now , add the below lines to your code.py

urls = ( '/', 'index' )

In this first part is regular expression that matches the URL and the second part is the name of a class to send the incoming request.Have to write the "index" method now.Open up the code.py and add a method called index , we can first try to print a "HELLO WORLD" on browser using web.py.

class index: def GET(self): print "HELLO WORLD"

This GET function will now get called by web.py anytime someone makes a GET request for "/".Need to finish up this with a final line telling web.py to start serving web pages:

if name == "main": web.run(urls, globals())

This tells web.py to serve the URLs we listed above and looking up the classes in the global namespace of this file.

Now run on your shell

$python code.py

The internal server of web.py gets started now , by default it will start at port number 8080 , you can change it by specifying the port you wish to run the server.

Adding templates

We can add all the templates to some directory , lets say templates , now add an index.html inside that.We can use either use simple html or web.py's templating language to add code to our HTML.

<em>HELLO WORLD</em>

To get these templates inside our application add a line to code.py

render = web.template.render('templates/')

Databasing

Before start using a database, make sure that you have the appropriate database library installed. For MySQL databases, use MySQLdb and for Postgres use psycopg2.Now above our web.run line add the following line to connect to database.

web.config.db_parameters = dict(dbn='postgres', user='username', pw='password', db='databasename')

This will connect to our database.Now you can make try on a simple application which will create a blogging system.You can give a try on simple application which will create a blogging system. blog.zip