Processing user Input
Lets start with a basic page with a form.
<html>
<body>
<form action='cgi-bin/hello2.py' method='get'>
<label for="myname">Enter Your Name</label>
<input id="myname" type="text" name="firstname" value="Nada" />
<input type="submit">
</form>
</body>
</html>
- method: this tells the browser which http method to use when submitting the form back to the server. The options are
get
orpost
. - action: This tells the browser the URL to use when submitting the form.
submit
renders as a button in the form. The purpose of this input type is to cause the form to be submitted back to the web server.#!/usr/bin/env python
import os
print "Content-type: text/html\n"
qs = os.environ['QUERY_STRING']
if 'firstname' in qs:
name = qs.split('=')[1]
else:
name = 'No Name Provided'
print "<html>"
print "<body>"
print "<h1>Hello %s</h1>" % name
print "</pre>"
print "</body>"
print "</html>"
QUERY_STRING
environment variable contains the string firstname. Note that that firstname in the query string corresponds to the name
attribute of the input element.When you press the submit button for a form, the web browser iterates over all of the input elements in the form, and collects the name value attributes of each. These are put together into a string that becomes part of the URL. The name value pairs are added after the usual URL information using the form:
?firstname=Sheldon&lastname=Cooper
The ?
separates the query string information from the URL itself. The &
separates each name value pair.The following figure gives you a good sense for the flow of how our little application works.
Combining into One File
Lets now combine our application into a single file. Using the following flow:- If there is no QUERY_STRING simply return the HTML for the form.
- If there is a QUERY_STRING then do not display the form, simply display the Hello greeting to the name stored in the QUERY STRING.
#!/usr/bin/env python
import os
headers = ["Content-type: text/html"]
qs = os.environ['QUERY_STRING']
def sendHeaders():
for h in headers:
print h
print "\n"
def sendForm():
print '''
<html>
<body>
<form action='cgi-bin/hellobetter.py' method='get'>
<label for="myname">Enter Your Name</label>
<input id="myname" type="text" name="firstname" value="Nada" />
<input type="submit">
</form>
</body>
</html>
'''
def sendPage(name):
print '''
<html>
<body>
<h1>Hello {0}</h1>
</body>
</html>
'''.format(name)
if not qs:
sendHeaders()
sendForm()
else:
if 'firstname' in qs:
name = qs.split('=')[1]
else:
name = 'No Name Provided'
sendHeaders()
sendPage(name)
The other functions,
sendPage
and sendForm
reduce the number of print statements we need by making use of Python’s triple quoted strings, and string formatting.
No comments:
Post a Comment