[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

When this form’s Submit button (labeled “Send” by the page’s HTML) is pressed, it
causes the script in Example 15-10 to be executed on the server machine, with the
inputs typed by the user.


Example 15-10. PP4E\Internet\Web\cgi-bin\tutor4.py


#!/usr/bin/python
"""
runs on the server, reads form input, prints HTML;
URL http://server-name/cgi-bin/tutor4.py
"""


import cgi, sys
sys.stderr = sys.stdout # errors to browser
form = cgi.FieldStorage() # parse form data
print('Content-type: text/html\n') # plus blank line


class dummy:


def init(self, s): self.value = s


form = {'user': dummy('bob'), 'age':dummy('10')}


html = """


tutor4.py

Greetings




%s


%s


%s



"""

if not 'user' in form:
line1 = 'Who are you?'
else:
line1 = 'Hello, %s.' % form['user'].value


line2 = "You're talking to a %s server." % sys.platform


line3 = ""
if 'age' in form:
try:
line3 = "Your age squared is %d!" % (int(form['age'].value) 2)
except:
line3 = "Sorry, I can't compute %s
2." % form['age'].value


print(html % (line1, line2, line3))


The table layout comes from the HTML file, not from this Python CGI script. In fact,
this script doesn’t do much new—it uses string formatting to plug input values into
the response page’s HTML triple-quoted template string as before, this time with one
line per input field. When this script is run by submitting the input form page, its output
produces the new reply page shown in Figure 15-11.


Climbing the CGI Learning Curve| 1159
Free download pdf