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

(yzsuai) #1

data is embedded in the data streams much like query parameters and form fields, but
it is contained in HTTP headers, not in a page’s HTML. Moreover, cookie data can be
stored permanently on the client, and so it outlives both pages and interactive sessions.


For web application developers, Python’s standard library includes tools that simplify
the task of sending and receiving: http.cookiejar does cookie handling for HTTP cli-
ents that talk to web servers, and the module http.cookies simplifies the task of creating
and receiving cookies in server-side scripts. Moreover, the module urllib.request
we’ve studied earlier has support for opening URLs with automatic cookie handling.


Creating a cookie


Web browsers such as Firefox and Internet Explorer generally handle the client side of
this protocol, storing and sending cookie data. For the purpose of this chapter, we are
mainly interested in cookie processing on the server. Cookies are created by sending
special HTTP headers at the start of the reply stream:


Content-type: text/html
Set-Cookie: foo=bar;

<HTML>...

The full format of a cookie’s header is as follows:


Set-Cookie: name=value; expires=date; path=pathname; domain=domainname; secure

The domain defaults to the hostname of the server that set the cookie, and the path
defaults to the path of the document or script that set the cookie—these are later
matched by the client to know when to send a cookie’s value back to the server. In
Python, cookie creation is simple; the following in a CGI script stores a last-visited time
cookie:


import http.cookies, time
cook = http.cookies.SimpleCookie()
cook['visited'] = str(time.time()) # a dictionary
print(cook.output()) # prints "Set-Cookie: visited=1276623053.89"
print('Content-type: text/html\n')

The SimpleCookie call here creates a dictionary-like cookie object whose keys are strings
(the names of the cookies), and whose values are “Morsel” objects (describing the
cookie’s value). Morsels in turn are also dictionary-like objects with one key per cookie
property: path and domain, expires to give the cookie an expiration date (the default is
the duration of the browser session), and so on. Morsels also have attributes—for in-
stance, key and value give the name and value of the cookie, respectively. Assigning a
string to a cookie key automatically creates a Morsel from the string, and the cookie
object’s output method returns a string suitable for use as an HTTP header; printing
the object directly has the same effect, due to its str operator overloading. Here is
a more comprehensive example of the interface in action:


>>> import http.cookies, time
>>> cooks = http.cookies.SimpleCookie()

1178 | Chapter 15: Server-Side Scripting

Free download pdf