Create dynamic Web pages, fast

author-image
CIOL Bureau
Updated On
New Update

Kenneth Gonsalves

Advertisment

Python is a scripting language which is rapidly taking the world by storm. It runs on
all platforms. Don’t worry if you don’t know python - any reasonably competent
programmer can learn python in a day. This tutorial deals with creating 'quicky' dynamic
web pages using python.

You need:

Advertisment

1. Python preferrably version 2.3: http://www.python.org

2. Cheetah ver 0.9.15 or later: http://www.CheetahTemplate.org

Advertisment

3. A text editor (or use idle, the IDE that comes with python)

4. An HTML editor (Quanta plus is a good choice)

5. A browser to view your pages

Advertisment

6. An HTTP server to test your application (Apache?)

We will be creating a simple user registration form. The coding is in two parts:

Advertisment

1. Create a template in html

2. Create a script in Python to populate the template and read and

Advertisment

validate data from it

We will also be following the three fundamental principles of Web programming:

Advertisment

1. Don’t put HTML in your code.

2. Don’t put code in your HTML.

3. Don’t use JavaScript for validation

The registration form will need the following details:

1. Salutation: Mr, Ms, Dr and Mrs - radiobuttons

2. Name: leading and trailing spaces and non-alphanumeric characters not

allowed

3. Interests: Checkboxes

4. City: List select

Here is a screenshot of the running application:

HEIGHT="399">

 

 

Here is the complete Python code:

(remember that indentation is part of the python syntax and the script will not run if
the indentation is changed). Note that the code can be condensed a lot, but I have made it
verbose so that it is self-explanatory

registration.py:

#######################################


#!/usr/bin/python #put your path to python


from Cheetah.Template import Template


import cgi


#to get meaningful error messages


import cgitb


cgitb.enable()


ok = False


msg = ''


theform = cgi.FieldStorage()


#this records the form output


parms = {'name':'','sal':'','city':'','interest':<>,'title':'Registration Form'}


sals = {'Mr':'checked','Ms':'','Dr':'','Mrs':''}


cities = {'Bangalore':'selected','Chennai':'','Mumbai':''}


interests = {'Girls':'','Boys':'','Music':'','Loafing':''} #none selected


if theform.has_key('name'):


        parms<'name'> =
theform.getfirst('name').strip()


        #strip() removes leading and trailing spaces


        ok = True


        #if the name is there the form is complete


        for ch in parms<'name'>:


            if ch in
"!@#$%^&*()<>.,/\+-=":



                msg
+= " Illegal Character: "+ch+', '



                ok
= False


       if theform.has_key('interest'):


            parms<'interest'> =
theform.getlist('interest') #this is a list


            #check the selected
interests


            for k in
interests.keys():



                        if
k in parms<'interest'>:



                            interests
= 'checked'



                       else:



                               interests
= ''


        parms<'sal'> = theform.getfirst('sal')


        #check the selected salutation


        for k in sals.keys():



                    if
k == parms<'sal'>:



                        sals
= 'checked'



                    else:



                        sals
= ''


parms<'city'> = theform.getfirst('city')


#select the selected city


       for k in cities.keys():



                if
k == parms<'city'>:



                        cities
= 'selected'



                else:



                        cities
= ''


if ok:


#save it or mail it or do something with it


        msg = 'Success: '+str(parms<'sal'>)+'
'+str(parms<'name'>)


        msg = msg +' City: '+str(parms<'city'>)+'
Interests: '


        for k in parms<'interest'>:



                    msg
= msg +' '+str(k)


#simplest way to create a cheetah template object


t = Template(file = 'registration.tmpl')


#add the variables to the template object


t.parms = parms


t.msg = msg


t.sals = sals


t.cities = cities


t.interests = interests


#output the template


print "Content-Type: text/html\n\n"


print t


######################################################

Here is the html template: href="https://www.ciol.com/images/content/2004/registration1.htm">registration.html:

#######################################################

Registration Form


color='blue'>$parms<'title'>




color='red'>$msg

#for $r in $sals

#end for

#for $cit in $cities

#end for

#for $ch in $interests

#end for

="" >$r
Name $parms<'name'>>
City
Interests
="" type="checkbox" value="$ch<br"/> name="interest" >$ch
value="Submit">

###########################################

Note:

Copy both registration.py and registration.tmpl into the cgi-bin directory of your Web
server. Make registration.py executable and access it from your browser:

http://localhost/cgi-bin/registration.py

The comments in the python code are self explanatory. We create lists of salutations,
cities and interests and pass them to the template. Template commands start with '#' sign
and template variables passed are identified by a leading '$' sign. This makes it easy for
the html designer to prettify his Web page without knowing anything about coding. You can
view the template file with the preview mode of your html editor which will show you the
relationship between the variables and the html code.

Play around with the code a bit and you'll see how to customise it or add new
components. Enter illegal characters in the 'Name' field to see how validation works. Note
how everything you enter is retained in the form.

The code is copylefted under the KGL (which means you can do whatever you want with it
as long as you dont blame me.

Mail me at lawgon at thenilgiris dot com with doubts, comments and flames.


tech-news