>>>
>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()
>>> print(reply)
b'<p>His name shall be... Set-Cookie: user=Brian</p>\n'
>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()
>>> print(reply)
b'<p>Welcome back, Brian</p>\n'
>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()
>>> print(reply)
b'<p>Welcome back, Brian</p>\n'
This works because urllib.request mimics the cookie behavior of a web browser on
the client—it stores the cookie when so requested in the headers of a script’s reply, and
adds it to headers sent back to the same script on subsequent visits. Also just as in a
browser, the cookie is deleted if you exit Python and start a new session to rerun this
code. See the library manual for more on this module’s interfaces.
Although easy to use, cookies have potential downsides. For one, they may be subject
to size limitations (4 KB per cookie, 300 total, and 20 per domain are one common
limit). For another, users can disable cookies in most browsers, making them less suited
to critical data. Some even see them as intrusive, because they can be abused to track
user behavior. (Many sites simply require cookies to be turned on, finessing the issue
completely.) Finally, because cookies are transmitted over the network between client
and server, they are still only as secure as the transmission stream itself; this may be an
issue for sensitive data if the page is not using secure HTTP transmissions between
client and server. We’ll explore secure cookies and server concepts in the next chapter.
For more details on the cookie modules and the cookie protocol in general, see Python’s
library manual, and search the Web for resources. It’s not impossible that future mu-
tations of HTML may provide similar storage solutions.
Server-Side Databases
For more industrial-strength state retention, Python scripts can employ full-blown da-
tabase solutions in the server. We will study these options in depth in Chapter 17.
Python scripts have access to a variety of server-side data stores, including flat files,
persistent object pickles and shelves, object-oriented databases such as ZODB, and
relational SQL-based databases such as MySQL, PostgreSQL, Oracle, and SQLite. Be-
sides data storage, such systems may provide advanced tools such as transaction com-
mits and rollbacks, concurrent update synchronization, and more.
Full-blown databases are the ultimate storage solution. They can be used to represent
state both between the pages of a single session (by tagging the data with generated
per-session keys) and across multiple sessions (by storing data under per-user keys).
Given a user’s login name, for example, CGI scripts can fetch all of the context we have
gathered in the past about that user from the server-side database. Server-side databases
Saving State Information in CGI Scripts| 1181