Cookies

web2py uses the Python cookies modules for handling cookies.

Cookies from the browser are in request.cookies and cookies sent by the server are in response.cookies.

You can set a cookie as follows:

  1. response.cookies['mycookie'] = 'somevalue'
  2. response.cookies['mycookie']['expires'] = 24 * 3600
  3. response.cookies['mycookie']['path'] = '/'

The second line tells the browser to keep the cookie for 24 hours. The third line tells the browser to send the cookie back to any application (URL path) at the current domain. Note, if you do not specify a path for the cookie, the browser will assume the path of the URL that was requested, so the cookie will only be returned to the server when that same URL path is requested.

The cookie can be made secure with:

  1. response.cookies['mycookie']['secure'] = True

This tells the browser only to send the cookie back over HTTPS and not over HTTP.

The cookie can be retrieved with:

  1. if request.cookies.has_key('mycookie'):
  2. value = request.cookies['mycookie'].value

Unless sessions are disabled, web2py, under the hood, sets the following cookie and uses it to handle sessions:

  1. response.cookies[response.session_id_name] = response.session_id
  2. response.cookies[response.session_id_name]['path'] = "/"

Note, if a single application includes multiple subdomains, and you want to share the session across those subdomains (e.g., sub1.yourdomain.com, sub2.yourdomain.com, etc.), you must explicitly set the domain of the session cookie as follows:

  1. if not request.env.remote_addr in ['127.0.0.1', 'localhost']:
  2. response.cookies[response.session_id_name]['domain'] = ".yourdomain.com"

The above can be useful if, for example, you want to allow the user to remain logged in across subdomains.