Marshal Cookie

MarshalCookie is a subclass of SignedCookie. It can store any marshallable object with the assurance that if the data is tampered the script can notice it.

If the stored hash is wrong then the marshal cookie will be "downgraded" to a base cookie.

As of mod_python 3.2.10 an exception will be raised and not catched if the scritp tries to parse Marshal cookies when there is any Signed cookie in the same path. So do not use both Signed and Marshal cookies in the same path of a site.

This sample stores a dictionary in the cookie:

from mod_python import Cookie
import time

def index(req):

   # A secret non-empty string to sign the cookie
   secret = 'my_secret'

   # Pass the cookie class and the secret to get_cookies() 
   marshal_cookies = Cookie.get_cookies(
      req, Cookie.MarshalCookie, secret=secret)

   # Get the returned marshalled cookie
   returned_marshal = marshal_cookies.get('marshal', None)
   
   # If the marshal cookie exists 
   if returned_marshal:
      # Check if the cookie was not altered
      if type(returned_marshal) is not Cookie.MarshalCookie:
         message = 'The cookie was altered'
      else:
         message = 'The cookie was not altered and the value is "%s"'
         message %= returned_marshal.value
   else:
      message = 'This is your first visit'

   # Create a marshal cookie
   send_marshal = Cookie.MarshalCookie(
      'marshal', {'key1':'data1', 'key2':'data2'}, secret)

   # The cookie will expire in 30 days.
   send_marshal.expires = time.time() + 30 * 24 * 60 * 60
   
   # Add the cookie to the HTTP header.
   Cookie.add_cookie(req, send_marshal)

   return """\
<html><body>
<p>%s</p>
<p><pre>%s</pre></p>
<p>%s</p>
</body></html>
""" % ('You have just received this cookie:', send_marshal, message)