Web and Database Development Environment Python Example

Please go through the HTML Example before doing this example.

Create a sample python file

  1. Go to the examples sub-directory of your web development directory and list the contents of the directory that end in .py:

    [username@l-lnx101 username]$ cd /webdev/user/username/examples
    [username@l-lnx101 examples]$ ls *.py
    sample_mysql.py  sample_psql.py

  2. There are two scripts which are example of using python to connect to a mysql database and a postgresql database. You can edit/view them with nano by typing nano sample_mysql.py or nano sample_psql.py.
  3. Using nano, we can create tutorial.py:

    [username@l-lnx101 examples]$ nano tutorial.py

  4. Copy and paste the following code into your nano screen (remember that white space is important in python, so it has to match exactly):

    import socket
    from cgi import escape
    from urllib import unquote
    def application(environ, start_response):
      status = '200 OK'

      # Get IP information
      client_ip = environ['REMOTE_ADDR']
      hostname = socket.gethostbyaddr(client_ip)[0]

      # Generate html
      output = '<html><head><title>Sample Python Script</title></head>\n<body>\n'
      output +='REMOTE_ADDR is '+client_ip + ' <br> \n'
      output +="Lookup of "+client_ip+" is <b>"+hostname+"</b><br> \n"
      output += "</body></html>\n"

      # Return web page
      response_headers = [('Content-type', 'text/html')]
      start_response(status, response_headers)
      return [output]

  5. Save the file and go to http://webdev.cs.uiowa.edu/~username/examples/tutorial.py where username is replaced with your divmsid.
  6. The page when viewed on l-lnx100 in the lab looks like:

    Lookup of is l-lnx100.divms.uiowa.edu