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

(yzsuai) #1
>>> cooks['visited'] = time.asctime()
>>> cooks['username'] = 'Bob'
>>> cooks['username']['path'] = '/myscript'

>>> cooks['visited'].value
'Tue Jun 15 13:35:20 2010'
>>> print(cooks['visited'])
Set-Cookie: visited="Tue Jun 15 13:35:20 2010"
>>> print(cooks)
Set-Cookie: username=Bob; Path=/myscript
Set-Cookie: visited="Tue Jun 15 13:35:20 2010"

Receiving a cookie


Now, when the client visits the page again in the future, the cookie’s data is sent back
from the browser to the server in HTTP headers again, in the form “Cookie:
name1=value1; name2=value2 ...”. For example:


Cookie: visited=1276623053.89

Roughly, the browser client returns all cookies that match the requested server’s do-
main name and path. In the CGI script on the server, the environment variable
HTTP_COOKIE contains the raw cookie data headers string uploaded from the client; it
can be extracted in Python as follows:


import os, http.cookies
cooks = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
vcook = cooks.get("visited") # a Morsel dictionary
if vcook != None:
time = vcook.value

Here, the SimpleCookie constructor call automatically parses the passed-in cookie data
string into a dictionary of Morsel objects; as usual, the dictionary get method returns
a default None if a key is absent, and we use the Morsel object’s value attribute to extract
the cookie’s value string if sent.


Using cookies in CGI scripts


To help put these pieces together, Example 15-16 lists a CGI script that stores a client-
side cookie when first visited and receives and displays it on subsequent visits.


Example 15-16. PP4E\Internet\Web\cgi-bin\cookies.py


"""
create or use a client-side cookie storing username;
there is no input form data to parse in this example
"""


import http.cookies, os
cookstr = os.environ.get("HTTP_COOKIE")
cookies = http.cookies.SimpleCookie(cookstr)
usercook = cookies.get("user") # fetch if sent


if usercook == None: # create first time


Saving State Information in CGI Scripts| 1179
Free download pdf