Home > Cherrypy, Programming, Python, Tutorials > How to use cookies with CherryPy

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 """
              <form id="
login" action="/doLogin/" method="post">
              <label>
              Username:
              <input name="
username" type="text" />
              </label>
              <label>
              Password:
              <input name="
password" type="password" />
              </label>
              <input type="
submit" value="Login" />
              </form>
           "
""

  @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 <a href="/doLogout/">logout</a>.’

  @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 <a href="/">login</a> 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.

Related posts:

  1. Number converter
  2. Windows 7 Login Error “The referenced account is currently locked out and may not be logged on to”

Categories: Cherrypy, Programming, Python, Tutorials Tags:
  1. No comments yet.
  1. No trackbacks yet.
*