Unique Fields

When a field is uniquely named, as in there is one only field with that name, then the getfirst() method of the FieldStorage object should be used. It will take, as the name implies, the value of the first field with that name. It will avoid introduced errors like when, as example, a curious user types the field twice in the address bar.

<html><body>
<%
import cgi

# Mentionining the form variable instantiates a FieldStorage object
# The getfirst() method is tailored to get uniquely named fields
word = form.getfirst('word')

if not word:
   #
%>
<form method="get" action="">
<p>Type a word: <input type="text" name="word">
<input type="submit" value="Submit"</p>
</form>
<%
else:
   # Escape the user input to avoid script injection attacks
   word = cgi.escape(word)
   #
%>
<p>The submitted word was "<%= word %>"</p>
<p><a href="?">Submit another word!</a></p>
<%
#
%>
</body></html>

If the user inputed data is to be shown in a HTML document then it is necessary to escape it from HTML tags or else everything inside < > will be interpreted by the HTML parser including javascript code like
<script type="text/javascript"> malicious code here </script>

The cgi.escape() method will transform the above into safe HTML text:
&lt;script type="text/javascript"&gt; malicious code here &lt;/script&gt;

This is useful not only to prevent script injection but also to make it possible to display HTML source code as has just been done above.