web.py – Introduction

Web.py is a web framework for python. You can install it in your Linux by running ‘sudo easy_install web.py’ in your terminal.
Here I would like to share a simple problem and solution that would introduce you into web.py. The problem is ‘ make a root webpage with an option to read name from a text box and a submit button to submit it. Upon submission the name should be saved on a text file and this file should be displayed on another webpage.’

Here is the solution with explanation:

import web

# '/' indicate root,for the root page request home class will be called.
# request for the url '/names' will call hello class

urls = (
  '/names', 'hello','/','home') 

app = web.application(urls, globals(), True)

# upon the GET request for the url '/names', the hello class return the 
#text file which contain the names

class hello:
    def GET(self):
        text = f.read()
        return text

#the home class has two functions to handle GET and POST request from web
#browser. Upon the GET request it return a html webpage.
#The POST function is called when we submit the html form and it write 
# the names to a text file.

class home:
    def GET(self):

        <form name="form" method="POST">
        Name: <input type="text" name="user" />
        <input type="submit" value="Submit" />

    def POST(self):
        form_name =  web.input()
        f = open("file.txt","a")
        raise web.seeother('/names')

if __name__ == "__main__":

How to run this program :
1.Save this program with an extension .py (say code1.py).
2.On the terminal type ‘python sample.py’ . Then on terminal you can see

Terminal Display

3. Now go to your browser and type ‘http://0.0.0:8080&#8217; .A simple page will be displayed.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s