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

(yzsuai) #1
far or by sending the server an explicit URL (Internet address) string that contains inputs
at the end. Such an explicit URL can be sent to a server either inside or outside of a
browser; in a sense, it bypasses the traditional input form page.
For instance, Figure 1-12 shows the reply generated by the server after typing a URL of
the following form in the address field at the top of the web browser (+ means a space
here):
http://localhost/cgi-bin/cgi101.py?user=Sue+Smith

Figure 1-12. cgi101.py reply to GET-style query parameters

The inputs here, known as query parameters, show up at the end of the URL after
the ?; they are not entered into a form’s input fields. Adding inputs to URLs is some-
times called a GET request. Our original input form uses the POST method, which
instead ships inputs in a separate step. Luckily, Python CGI scripts don’t have to dis-
tinguish between the two; the cgi module’s input parser handles any data submission
method differences for us.
It’s even possible, and often useful, to submit URLs with inputs appended as query
parameters completely outside any web browser. The Python urllib m o d u l e p a c k a g e ,
for instance, allows us to read the reply generated by a server for any valid URL. In
effect, it allows us to visit a web page or invoke a CGI script from within another script;
your Python code, instead of a browser, acts as the web client. Here is this module in
action, run from the interactive command line:
>>> from urllib.request import urlopen
>>> conn = urlopen('http://localhost/cgi-bin/cgi101.py?user=Sue+Smith')
>>> reply = conn.read()
>>> reply
b'<title>Reply Page</title>\n<h1>Hello <i>Sue Smith</i>!</h1>\n'

>>> urlopen('http://localhost/cgi-bin/cgi101.py').read()
b'<title>Reply Page</title>\n<h1>Who are you?</h1>\n'

>>> urlopen('http://localhost/cgi-bin/cgi101.py?user=Bob').read()
b'<title>Reply Page</title>\n<h1>Hello <i>Bob</i>!</h1>\n'

58 | Chapter 1: A Sneak Preview

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf