How to use cookies with CherryPy

Introduction

CherryPy uses the Cookie module from Python and in particular the SimpleCookie object type to handle cookies.

Sending a cookie to a browser is accomplished by using cherrypy.response.cookie and receiving a cookie from the browser by cherrypy.request.cookie.

Example

This is demonstrated in the following example code where we use a login and logout procedure :

import cherrypy

class Root(object):
  @cherrypy.expose
  def index(self):
    return """
              
""" @cherrypy.expose def doLogin(self, username, password): # Set cookie to send cookie = cherrypy.response.cookie cookie['user'] = username cookie['user']['path'] = '/' cookie['user']['max-age'] = 3600 cookie['pass'] = password cookie['pass']['path'] = '/' cookie['pass']['max-age'] = 3600 return 'Cookie set. You can now logout.' @cherrypy.expose def doLogout(self): # Request cookie that is already set reqcookie = cherrypy.request.cookie # Response cookie that overwrites the old one and expires rescookie = cherrypy.response.cookie for name in reqcookie.keys(): rescookie[name] = name rescookie[name]['path'] = '/' rescookie[name]['max-age'] = 0 # or: rescookie[name]['expires'] = 0 return 'Logged out succesfully. You can now login again.' cherrypy.quickstart(Root())

Download source code

Creating a cookie

It is important to note that

  • cookie[name]
  • cookie[name][‘path’]
  • cookie[name][‘max-age’]

are a bare minimum of attributes that you have to set in order to get this working. If you do not set one of these three attributes, the cookie will simply not be set.

Deleting a cookie

Instead of cookie[name][‘max-age’]=0 you can also use cookie[name][‘expires’]=0, which results in the same effect of deleting the cookie.