Cookies

You can read cookies through the request object, and construct cookies using the functions in pesto.cookies.

Setting cookies

Simply assign an instance of pesto.cookie.Cookie to a set-cookie header:

def handler(request):
    return Response(
        ['blah'],
        set_cookie=pesto.cookie.Cookie(
            name='partnumber',
            value='Rocket_Launcher_0001',
            path='/acme',
            maxage=3600,
            domain='example.com'
        )
    )

Clearing cookies

To expire a cookie is to clear it. Set a new cookie with the same details as the one you are clearing, but with no value and maxage=0:

def handler(request):
    return Response(
        [],
        set_cookie=pesto.cookie.Cookie(
            name='partnumber',
            value='',
            path='/acme',
            maxage=0,
            domain='example.com'
        )
    )

pesto.cookie API documention

class pesto.cookie.Cookie(name, value, maxage=None, expires=None, path=None, secure=None, domain=None, comment=None, http_only=False, version=1)

Represents an HTTP cookie.

See rfc2109, HTTP State Management Mechanism

>>> from pesto.cookie import Cookie
>>> c = Cookie('session_id', 'abc123')
>>> c.path = '/cgi-bin'
>>> c.domain = '.ucl.ac.uk'
>>> c.path
'/cgi-bin'
>>> print str(c)
session_id=abc123;Domain=.ucl.ac.uk;Path=/cgi-bin;Version=1

Initialize a Cookie instance.

expires

Return the cookie expires value as an instance of datetime.

get_expires()

Return the cookie expires value as an instance of datetime.

set_expires(dt)

Set the cookie expires value to datetime object dt

Synopsis:

>>> from pesto.testing import TestApp
>>> from pesto.response import Response
>>> from pesto import to_wsgi
>>>
>>> def handler(request):
...     return Response(set_cookie = expire_cookie('Customer', path='/'))
...
>>> TestApp(
...     to_wsgi(handler),
...     HTTP_COOKIE='''$Version="1";
...     Customer="WILE_E_COYOTE";
...     Part="Rocket_0001";
...     Part="catapult_0032"
... ''').get().get_header('Set-Cookie')
'Customer=;Expires=Tue, 01 Jan 1980 00:00:00 -0000;Max-Age=0;Path=/;Version=1'

Return a list of Cookie objects read from the request headers.

Parameters:
  • cookie_string – The cookie, eg CUSTOMER=FRED; path=/;
  • unquote – A function to decode quoted values. If set to None, values will be left as-is.

See rfc2109, section 4.4

The Cookie header should be a ‘;’ separated list of name value pairs. If a name is prefixed by a ‘$’, then that name is an attribute of the most recently (left to right) encountered cookie. If no cookie has yet been parsed then the value applies to the cookie mechanism as a whole.

Table Of Contents

Previous topic

URL dispatch

Next topic

Session storage

This Page