cookies = http.cookies.SimpleCookie() # print Set-cookie hdr
cookies['user'] = 'Brian'
print(cookies)
greeting = '
His name shall be... %s
' % cookies['user']else:
greeting = '
Welcome back, %s
' % usercook.valueprint('Content-type: text/html\n') # plus blank line now
print(greeting) # and the actual html
Assuming you are running this chapter’s local web server from Example 15-1, you can
invoke this script with a URL such as http://localhost/cgi-bin/cookies.py (type this in
your browser’s address field, or submit it interactively with the module url
lib.request). The first time you visit the script, the script sets the cookie within its
reply’s headers, and you’ll see a reply page with this message:
His name shall be... Set-Cookie: user=Brian
Thereafter, revisiting the script’s URL in the same browser session (use your browser’s
reload button) produces a reply page with this message:
Welcome back, Brian
This occurs because the client is sending the previously stored cookie value back to the
script, at least until you kill and restart your web browser—the default expiration of a
cookie is the end of a browsing session. In a realistic program, this sort of structure
might be used by the login page of a web application; a user would need to enter his
name only once per browser session.
Handling cookies with the urllib.request module
As mentioned earlier, the urllib.request module provides an interface for reading the
reply from a URL, but it uses the http.cookiejar module to also support storing and
sending cookies on the client. However, it does not support cookies “out of the box.”
For example, here it is in action testing the last section’s cookie-savvy script—cookies
are not echoed back to the server when a script is revisited:
>>> from urllib.request import urlopen
>>> reply = urlopen('http://localhost/cgi-bin/cookies.py').read()
>>> print(reply)
b'<p>His name shall be... Set-Cookie: user=Brian</p>\n'
>>> reply = urlopen('http://localhost/cgi-bin/cookies.py').read()
>>> print(reply)
b'<p>His name shall be... Set-Cookie: user=Brian</p>\n'
To support cookies with this module properly, we simply need to enable the cookie-
handler class; the same is true for other optional extensions in this module. Again,
contacting the prior section’s script:
>>> import urllib.request as urllib
>>> opener = urllib.build_opener(urllib.HTTPCookieProcessor())
>>> urllib.install_opener(opener)
1180 | Chapter 15: Server-Side Scripting