Sending Data to an HTML File : CGI « Network « Python






Sending Data to an HTML File

 

File:demo.py

#!c:/Python25/python
import cgi

def send_form( dic ) :
    fName = dic.getvalue("firstname", "" )
    lName = dic.getvalue("lastname", "" )

    flag = int( dic.getvalue("flag", "0") )

    print "<form action=\"demo.py\">"
    if flag == 1 and fName == "" :
        print "<p><FONT COLOR='red'>Enter your first name:</FONT></p>"
    else :
        print "<p>Enter your first name:</p>"

    if fName != "" :
        print "<input type=\"text\" name=\"firstname\" value=\""+fName+"\" size=\"40\">"
    else :
        print "<input type=\"text\" name=\"firstname\" size=\"40\">"

    if flag == 1 and lName == "" :
        print "<p><FONT COLOR='red'>Enter your last name:</FONT></p>"
    else :
        print "<p>Enter your last name:</p>"
    if lName != "" :
        print "<input type=\"text\" name=\"lastname\" value=\""+lName+"\" size=\"40\">"
    else :
        print "<input type=\"text\" name=\"lastname\" size=\"40\">"
    print "<p>"
    print "<input type=\"submit\">"
    print "<input type=\"reset\">"
    print "<input type=\"hidden\" name=\"flag\" value=\"1\">"
    print "</p>"

def gen_output( dic ) :

    error = 0

    fName = dic.getvalue("firstname", "" )
    lName = dic.getvalue("lastname", "" )

    if fName == "" or lName == "" :
        error = 1

    if error == 0 :
        print "Hello there " + fName + " " + lName
    return error

print "Content-Type: text/html\n\n"
print "<HTML>"
form = cgi.FieldStorage()
res = gen_output(form)
if res == 1:
    send_form(form)
print "<form>"
print "</html>"

   
  








Related examples in the same category

1.Get form value
2.Get and set Cookies
3.Uploading Files
4.Redirection