16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 15 ■ PYTHON AND THE WEB 327<br />

A Simple Form<br />

Now you have the <strong>to</strong>ols for handling a user request; it’s time <strong>to</strong> create a form that the user can<br />

submit. That form can be a separate page, but I’ll just put it all in the same script.<br />

To find out more about writing HTML forms (or HTML in general), you should perhaps get<br />

a good book on HTML (your local books<strong>to</strong>re probably has several). You can also find plenty of<br />

information on the subject online. Here are some resources:<br />

• http://www.webreference.com/htmlform<br />

• http://www.htmlhelp.com/faq/html/forms.html<br />

• http://www.cs.tut.fi/~jkorpela/forms<br />

• http://www.htmlgoodies.com/tu<strong>to</strong>rs/fm.html<br />

Also, if you find some page that you think looks like a good example for what you’d like <strong>to</strong><br />

do, you can inspect its source in your browser by choosing View Source or something similar<br />

(depending on which browser you have) from one of the menus.<br />

Let’s return <strong>to</strong> our script. An extended version can be found in Listing 15-7. In the beginning,<br />

the CGI parameter name is retrieved, as before, with the default 'world'. If you just open<br />

the script in your browser without submitting anything, the default is used.<br />

Then, a simple HTML page is printed, containing name as a part of the headline. In addition,<br />

this page contains an HTML form whose action attribute is set <strong>to</strong> the name of the script itself<br />

(simple3.cgi). That means that if the form is submitted, you are taken back <strong>to</strong> the same script.<br />

The only input element in the form is a text field called name. Thus, if you submit the field with<br />

a new name, the headline should change because the name parameter now has a value.<br />

Listing 15-7. A Greeting Script with an HTML Form (simple3.cgi)<br />

#!/usr/bin/env python<br />

import cgi<br />

form = cgi.FieldS<strong>to</strong>rage()<br />

name = form.getvalue('name', 'world')<br />

print """Content-type: text/html<br />

<br />

<br />

Greeting Page<br />

<br />

<br />

Hello, %s!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!