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): f=open("file.txt",'r') text = f.read() f.close() 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): return''' <html> <head> <title>web.py</title> </head> <body> <form name="form" method="POST"> Name: <input type="text" name="user" /> <input type="submit" value="Submit" /> </form> </body> </html>''' def POST(self): form_name = web.input() f = open("file.txt","a") f.write(form_name.user) f.write("\n") f.close() 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
3. Now go to your browser and type ‘http://0.0.0:8080’ .A simple page will be displayed.