Lecture 50 + HW

posted May 6, 2013, 6:17 AM by Samuel Konstantinovich   [ updated May 6, 2013, 1:09 PM ]
Obtaining the values from the url:

We can send information to a web page using forms. One of the methods to do so is called 'get'. 

The values and variable names from using get are all displayed in the URL bar. 

Take for example a google search:
https://www.google.com/#sclient=psy-ab&q=get+form&fp=70061d209f991f76

notice there are some assignment like statements in the 
sclient=psy-ab
q=get+form


I. We can do the same thing in python:
    localhost:9000/cgi-bin/mypyfile.py?x=3&y=2&mode=maths&output=eng

we can retrieve the variable names and their values in python using cgi: (the following should be mypyfile.py)

#!/usr/bin/python
print 'Content-type: text/html\n\n'
import cgi
form=cgi.FieldStorage()

if len(form)>0:
        for key in form.keys():
            value=str(form[key].value)
            print 'Key: <b>'+str(key)+'</b>  Value: <b>'+value+'</b><br>'

    
II. A more elaborate example incorporates more HTML but keeps the same ideas if you save this in file.py:

#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
def doStuff(form):
    ans= form['a'].value+'x^2+'+form['b'].value+'x+'+form['c'].value+'<br>'                                           
    return ans
def main():
    HTML_HEADER='Content-type: text/html\n\n'
    page = HTML_HEADER
    page+='<html><body>Here is a quadratic:<br>'
    form=cgi.FieldStorage()
    if 'a' in form and 'b' in form.keys() and 'c' in form.keys():
            page+=doStuff(form)
    else:
        page+= 'Required fields missing: a, b, and c are required.<br>'
    page+= '</body></html>'
    print page    
main()

Now if you can use the file and provide values in the format:
http://server.com/file.py?a=13&b=2&c=3
http://server.com/file.py?b=2&c=3&a=32

If you forget one it tells you that you are missing something:
http://server.com/file.py?a=9&b=22

III. Finally Your Task: (complete for homework) Write a python page that calculates Area and Volume, then link your document in your home.html file:

    1. If the incorrect parameters are passed via the forms:
http://URL/file.py?length=3  would give a webpage:

Required fields missing: length and width are required, height is optional.

    2. If length and width are provided:   
http://URL/file.py?length=3&width=9  would give a webpage:

Area:
27   

    3. If length width and height are provided volume is calculated. e.g.   
http://URL/file.py?length=3&height=9&width=2  would give a webpage:
Volume:
54

Comments