Unique Fields
This script has two functions: fill() and show(). The former returns a form to be filled by the user and the later shows the submitted user data.
import cgi def fill(): s = """\ <html><body> <form method="get" action="./show"> <p>Type a word: <input type="text" name="word"> <input type="submit" value="Submit"</p> </form></body></html> """ return s # Receive the Request object def show(req): # The getfirst() method returns the value of the first field with the # name passed as the method argument word = req.form.getfirst('word', '') # Escape the user input to avoid script injection attacks word = cgi.escape(word) s = """\ <html><body> <p>The submitted word was "%s"</p> <p><a href="./fill">Submit another word!</a></p> </body></html> """ return s % word
It should be executed like this:
http://my_site.tld/dir/path/script/fill
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.
The show() function would be the same if the form used the post method to submit the data.
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:
<script type="text/javascript"> malicious code here </script>
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.
