#!/usr/bin/env python ''' cookies.py Jeff Ondich, 28 May 2012 A simple illustration of setting and retrieving cookies in HTTP server-side scripts. If the server-side script wants to store a small amount of data on the client, it can do so by sending a "Set-cookie: name=value" header along with the HTTP response. If the client (typically a web browser) accepts this cookie, then it will always send the cookie back to this server when making more queries. In this example, the first time the client visits cookies.py, we generate a new cookie with name "moose" and value "bullwinkle [time]" where "[time]" is the current time on the server's machine. We could just print "Set-cookie: moose=bullwinkle 09:35:12" after the Content-type line and before the blank line at the end of the HTTP response headers. But instead, we'll use Python's Cookie module to assemble the appropriate header. When the client visits cookies.py for a second time, the client's HTTP request headers will include a "Cookie: moose=bullwinkle 09:35:12" line. Python's Cookie module can be used to parse this line, as shown below. In this example, I added one extra feature. If you include "action=reset" as a GET or POST argument, this script tells the client to delete the moose cookie by setting its expiration time to now. ''' import os import cgi import Cookie import datetime def deleteMooseCookie(): cookie = Cookie.SimpleCookie() cookie['moose'] = '' cookie['moose']['expires'] = 0 print cookie.output() print 'Content-type: text/plain' print print 'Deleted the moose cookie' def getMooseCookieValue(): try: cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) return cookie['moose'].value except: return None def reportExistingMooseCookie(cookieValue): print 'Content-type: text/plain' print print 'The moose cookie already existed on the client, with value: ' + cookieValue def createMooseCookie(): dateString = datetime.datetime.now().strftime("%H:%M:%S") cookieValue = 'bullwinkle ' + dateString message = 'Created a new moose cookie: ' + cookieValue cookie = Cookie.SimpleCookie() cookie['moose'] = cookieValue print cookie.output() print 'Content-type: text/plain' print print 'The cookie has been created, with value: ' + cookieValue if __name__ == '__main__': cookieValue = getMooseCookieValue() arguments = cgi.FieldStorage() if 'action' in arguments and arguments['action'].value == 'reset': deleteMooseCookie() elif cookieValue is not None: reportExistingMooseCookie(cookieValue) else: createMooseCookie()