4.7.3 Examples

This example sets a simple cookie which expires in 300 seconds:

from mod_python import Cookie, apache
import time

def handler(req):

    cookie = Cookie.Cookie('eggs', 'spam')
    cookie.expires = time.time() + 300
    Cookie.add_cookie(req, cookie)

    req.write('This response contains a cookie!\n')
    return apache.OK

This example checks for incoming marshal cookie and displays it to the client. If no incoming cookie is present a new marshal cookie is set. This example uses "secret007" as the secret for HMAC signature.

from mod_python import apache, Cookie

def handler(req):

    cookies = Cookie.get_cookie(req, Cookie.MarshalCookie,
                                    secret='secret007')
    if cookies.has_key('spam'):
        spamcookie = cookies['spam']

        req.write('Great, a spam cookie was found: %s\n' \
                                      % str(spamcookie))
        if type(spamcookie) is Cookie.MarshalCookie:
            req.write('Here is what it looks like decoded: %s=%s\n'
                      % (spamcookie.name, spamcookie.value))
        else:
            req.write('WARNING: The cookie found is not a \
                       MarshalCookie, it may have been tapered with!')

    else:

        # MarshaCookie allows value to be any marshallable object
        value = {'egg_count': 32, 'color': 'white'}
        Cookie.add_cookie(req, Cookie.MarshalCookie('spam', value, \
                          'secret007'))
        req.write('Spam cookie not found, but we just set one!\n')

    return apache.OK

What is this????