1. Problem

You've written a site that requires cookie support in the client; the most common reason is using sessions. Good interface design requires that users get a warning if their browser doesn't support cookies; this is much better than just having the interface fail with no explanation. You want to check if the client supports cookies.

2. Solution

After storing some information in the session, ensuring that the session is marked as dirty and you can redirect the user to the following cookie_check handler:

def cookie_check [plain] (request, dest_url=""):
    # You only get redirected to this page once you've logged in,
    # and therefore will have a cookie.  If the request contains no cookies,
    # warn the user.
    if len(request.cookies) != 0:
        return request.redirect(dest_url or "/")
    standard.header("Cookies Not Enabled")
    """<p>Cookies do not seem to be enabled in your browser.
    <p>Please enable cookie support in your browser's preferences.
    """
    standard.footer()

This will check that the request contains at least one cookie, and reports an error to the user if it doesn't. If a cookie is found, the browser will be redirected to the top page of the site.

Alternatively, you can reference the function from another handler in order to specify a destination path other than "/".

def _q_index [html] (request):
    ...
    return cookie_check(request, '/destination')

3. Discussion

You might be tempted to use the HTTPRequest.guess_browser_version() instead of an explicit cookie check, but this is a mistake. Most browsers that support cookies provide a way to disable them or the option of disregarding certain cookies at user request, so you can't conclude that the client supports cookies just because it's Mozilla 5.0. Some browsers also provide ways to change the reported user agent, so the reported browser name and version can't be trusted.

Instead of waiting until the session contains some information, you could also just set a test cookie:

    request.response.set_cookie('test_cookie', '1', path='/')
    return request.redirect('cookie_check')


CategoryCookbook