Tuesday 26 July 2011

AJAX & web.py : some quick reference



This post will give you some basic ideas about how to use AJAX with web.py. 

You all know that web.py is a simple web framework for python,the main thing i liked about web.py is that it is very simple to use and more effective too.web.py frame work can run its own basic web server .

About AJAX(Asynchronous Java script and XML) you all know that it is very helpful to create interactive web applications.With Ajax, web applications can send data to, and retrieve data from, a server asynchronously , i.e you can updates the parts of web page without reloading the whole page.

So here i would like to describe some examples that we can experiment with AJAX & web.py.

The Ajax application that we are going to discuss here contain one "div" section and a button. The "div" section will be used to display the contents return form the server.


<html>
<body>
          
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>

</body>
</html>


With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post.And you can load remote data directly into selected HTML elements of your web page!

Next, add a <script> tag to the page's head section. The script section contains the AJAX load function.The jQuery load() method is a simple AJAX function. It has the following syntax:

$(selector).load(url,data,callback)

Next we are adding the <script> tag  under <head> section,This section contains jQuery load method.

<head>
      <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery 1.4.2.min.js"></script>
      <script type="text/javascript">
      $(document).ready(function(){
        $("button").click(function(){
           $("div").load("http://127.0.0.1:8080/static/test.txt");    
        });
      });
      </script>
 </head>



Here the  load function will load desired contents from the specified URL.(What this URL actually functions is described in the below section,you will get exact picture after you read the whole thing)

Next we are going to implement this code with web.py.


Before we move on to web.py,We have to create a folder named "static" in the same folder that your program resides,and put your text file (here the file is "test.txt" ) inside the "static" folder.Then check that you are able to access the file by typing the URL (" http://127.0.0.1:8080/static/test.txt ") in your browser search bar.If the browser displays the contents properly then you can implement this on aJax load function.


The whole program described below.


Program name -- Code.py

import web

  urls = (
    '/', 'main')


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


  class main:
      def GET(self):
          return'''
          <html>
          <head>
          <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
          <script type="text/javascript">
          $(document).ready(function(){
            $("button").click(function(){
              $("div").load("http://127.0.0.1:8080/static/test.txt");
            });
          });

          </script>
          </head>
          <body>
            
          <div><h2>Let AJAX change this text</h2></div>
          <button>Change Content</button>

          </body>
          </html>'''


  if __name__ == "__main__":
      app.run()


How to run the program:


Web.py comes with a built-in web server that you all know. We have created our program file called  " code.py ",just save the file and  run the following command in terminal to start your application.


sreehari@sreehari-desktop:~/web.py$ python code.py
  http://0.0.0.0:8080/



Then goto your browser and type " http://127.0.0.1:8080/ " in your search bar , you will get a web page with a text " Let AJAX change this text " and it also contains a button,when you hit the button the text will change and new text from the text file will be loaded and displayed in your browser.

Monday 18 July 2011

A simple exercise in web.py

 This is just a simple exercise that will help you to understand the basics of web.py.

Qn: Create a webpage that should contain a text box,so that you can input your names,the page should also provide a submit button to submit the details that you entered in a text box.when you submit it the names should be saved in a text file and whole the names that we entered should be displayed in another URL.

1st step: Import the module Web.py,to use the tools provided by web.py. Map the first URL (" / ") to a class named "main".and map the second URL ("/Details") to a class named  "details".


import web

  urls = (
    '/','main',
    '/Details','details')

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


2nd step: Next we have to define the class named "main".The function GET() is actually displays the content in your browser when you opens a webpage.When you opens the first page it should displays a form,so thats why ,we are writing the HTML code to create a form under GET() function.Here we are specifying the method attribute of form as POST to invoke the POST request .

class main:
    def GET(self):
    return'''
    <html>
    <head>
    <title>web.py</title>
    </head>

    <body>

    <h1>A simple exercise in web.py</h1>

    <form name="form" method = "POST">

    Name: <input type="text" name="user"/>

    <input type="submit" value="Submit" />

    </form>
    </body>
    </html>'''



3rd step: The GET() function that we introduced above will only serve the pages ,but here we have to update the values to another webpage.Thats why we are using a POST function.The line "form = web.input()" creates a storage objects that contains all  variables passed into it.Then we open a file named "file.txt" in append mode,then write the input values  into the file by using " f.write(form.user) ". Then Web.redirect('/Details') will redirect the user to a new URL(" /Details ") ,i.e when we submit the form it will guide you to the next page that contain all the details that you entered before.

def POST(self):

   form =  web.input()
   f=open("file.txt",'a')
   f.write(form.user)
   f.write("\n")
   f.close()

   raise web.redirect('/Details')

4th step: We have to define the class for the URL("/Define").Here we are using GET() function to display the contents.so to displays the contents in the text file we just simply opens the file in read mode.and then read the values by using "f.read()" function and then assigned it to a variable named data,when we return the variable it will displays all the values that we read from the text file in the next URL.

class details:

  def GET(self):

    f=open("file.txt",'r')
    data=f.read()
    return data
    f.close()


Complete code:


Program name: Code.py

import web

urls = (
  '/','main',
  '/Details','details')

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

class main:
   def GET(self):
    return'''
    <html>
    <head>
    <title>web.py</title>
    </head>

    <body>

    <h1>A simple exercise in web.py</h1>

    <form name="form" method = "POST">

    Name: <input type="text" name="user"/>

    <input type="submit" value="Submit" />

    </form>
    </body>
    </html>'''

    def POST(self):
 
      form =  web.input()
      f=open("file.txt",'a')
      f.write(form.user)
      f.write("\n")
      f.close()

    
      raise web.redirect('/Details')
    
class details:
    
    def GET(self):

      f=open("file.txt",'r')
      data=f.read()
      return data
      f.close()

if __name__ == "__main__":
    app.run()

Sunday 10 July 2011

Web.py : Installation and working


Web.py is a simple web frame work that is written in python for the development of python related web applications.The main feature about web .py is that it is very simple and efficient compared to others


Installation:-

  • Download web.py from the below link.Then extract and copy it into to any directory that your application resides or make it accessible to all applications.
  • Type "cd" in Terminal to "change the directory "where you copied web.py, If you list the contents you  can see a setup.py file inside it. To install the file type the below command.
                            python setup.py install.
  • when you found any permission denied messages when installing in unix like systems,switch to root user and then try the below command.
                            sudo python setup.py install


Working:-


    when you installed it properly you can try it by creating some simple webpages.Open any of your favorite  editor and  creating a file named "hello.py" as shown below.



import web

urls = (

  '/', 'hello')

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

class hello:

    def GET(self):

        return 'Hello, web!'

if __name__ == "__main__":

    app.run()



Here  first you need to import the module web.py to use the tools provided by web.py i.e the first line actually refers.


In the second line we are actually mapping the web address(URL) i.e "http://webpy.org/" to a python class    named "hello".


Inside the class you can see a function named  "GET()".This  function "GET()" is actually displays the content  in your browser when your browser opens a web page.Here it will display the string "Hello,web" .


In the third line we are creating an instance .It will handle the all duties like handling the browser request and   serving the desired pages.


The last line will start the web application to handle your requests.


Save the above file and run by using the command python hello.py.


when you run the file,the output will be the address of your website ,by default it is (http://localhost:8080/).    when you copy it and paste it in your browser search bar you will get the resultant web page.