Using cookies in TurboGears

TurboGears uses the CherryPy method of setting and reading cookies, which is to say it uses Python's Cookie.SimpleCookie object.

Setting a cookie

To set a cookie, you'll need to make sure cherrypy is imported and set a few options. Here's an example:

In this example, we've set up a cookie called userName that has the value "TurboGears User". More can be read about other options in the Python Cookie Module Documentation.

Reading a cookie

To read a cookie, we use the cherrypy.request.simpleCookie object. Let's say we want to find the value for the userName cookie:

It's as simple as that!

Deleting a cookie

Deleting cookies is not quite as straightforward as it would seem, but is nonetheless very easy. All you have to do is set the cookie's expiration to 0. Let's delete the userName cookie: