Subsections

18. How to use cookies with CherryPy

CherryPy uses the Cookie module from python and in particular the SimpleCookie object type to handle cookies. More information can be found here: http://www.python.org/doc/current/lib/module-Cookie.html

18.1 Setting cookies

In order to send a cookie to a browser, you have to use the global variable response.simpleCookie, which is a SimpleCookie object.

The following code shows how to set a cookie in your CherryPy code:

CherryClass Root:
view:
    def index(self):
        response.simpleCookie['cookieName']='cookieValue'
        response.simpleCookie['cookieName']['path']='/'
        response.simpleCookie['cookieName']['max-age']=3600
        response.simpleCookie['cookieName']['version']=1
        return "<html><body>Hello, I just sent you a cookie</body></html>"

18.2 Reading cookies

Cookies that are sent by a browser are stored in the global variable response.simpleCookie, which is a SimpleCookie object.

The following code shows how to read a cookie in your CherryPy code:

CherryClass Root:
mask:
    def index(self):
        <html><body>
            Hi, you sent me <py-eval="len(request.simpleCookie)"> cookies.<br>
            Here is a list of cookie names/values:<br>
            <py-for="cookieName in request.simpleCookie.keys()">
                <py-eval="cookieName+': '+request.simpleCookie[cookieName].value"><br>
            </py-for>
        </body></html>

See About this document... for information on suggesting changes.