Retrieve the Cookie
The returned cookie will be available as a string in the os.environ dictionary with the key 'HTTP_COOKIE':
cookie_string = os.environ.get('HTTP_COOKIE')
The load() method of the SimpleCookie object will parse that string rebuilding the object's mapping:
cookie.load(cookie_string)Complete code:
#!/usr/bin/env python import Cookie, os, time cookie = Cookie.SimpleCookie() cookie['lastvisit'] = str(time.time()) print cookie print 'Content-Type: text/html\n' print '<html><body>' print '<p>Server time is', time.asctime(time.localtime()), '</p>' # The returned cookie is available in the os.environ dictionary cookie_string = os.environ.get('HTTP_COOKIE') # The first time the page is run there will be no cookies if not cookie_string: print '<p>First visit or cookies disabled</p>' else: # Run the page twice to retrieve the cookie print '<p>The returned cookie string was "' + cookie_string + '"</p>' # load() parses the cookie string cookie.load(cookie_string) # Use the value attribute of the cookie to get it lastvisit = float(cookie['lastvisit'].value) print '<p>Your last visit was at', print time.asctime(time.localtime(lastvisit)), '</p>' print '</body></html>'
When the client first loads the page there will be no cookie in the client's computer to be returned. The second time the page is requested then the cookie saved in the last run will be sent to the server.