''' cookies.py Jeff Ondich, 28 May 2012 Tianna Avery, November 2018, updated for Python 3 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 http.cookies 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 http.cookies 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 http.cookies import datetime def delete_moose_cookie(): cookie = http.cookies.SimpleCookie() cookie['moose'] = '' cookie['moose']['expires'] = 0 print(cookie.output()) print('Content-type: text/plain') print() print('Deleted the moose cookie') def get_moose_cookie_value(): try: cookie = http.cookies.SimpleCookie(os.environ["HTTP_COOKIE"]) return cookie['moose'].value except: return None def report_existing_moose_cookie(cookie_value): print('Content-type: text/plain') print() print('The moose cookie already existed on the client, with value: ' + cookie_value) def create_moose_cookie(): date_string = datetime.datetime.now().strftime("%H:%M:%S") cookie_value = 'bullwinkle ' + date_string message = 'Created a new moose cookie: ' + cookie_value cookie = http.cookies.SimpleCookie() cookie['moose'] = cookie_value print(cookie.output()) print('Content-type: text/plain') print() print('The cookie has been created, with value: ' + cookie_value) if __name__ == '__main__': cookie_value = get_moose_cookie_value() arguments = cgi.FieldStorage() if 'action' in arguments and arguments['action'].value == 'reset': delete_moose_cookie() elif cookie_value is not None: report_existing_moose_cookie(cookie_value) else: create_moose_cookie()