Latest Version: 0.9.6.2
  Dashboard > Pylons Cookbook > ... > Getting Started > Setting cookies and response headers
  Pylons Cookbook Log In | Sign Up   View a printable version of the current page.  
  Setting cookies and response headers
Added by Max Ischenko, last edited by Mike Orr on Apr 17, 2008  (view change)
Labels: 

Pylons uses Paste to deal with HTTP responses which has a thin wrapper class around WSGI. This wrapper class is available as paste.Response and is already imported to your lib/base.py module.

To set cookies or some response header you invoke corresponding method of WSGIResponse instance. Starting from Pylons 0.9.6, there is a global response object you can modify directly. Pylons 0.9.7 uses WebOb's Request and Response objects, which have slightly different methods than the Request and Response used in Pylons 0.9.6 and earlier.

1
2
3
4
5
6
def setlang(self):
    #'response' is the ``pylons.response`` global.
    response.set_cookie('sitelang', 'uk', expires=3600) # Pylons 0.9.6 syntax.
    #response.set_cookie('sitelang', 'uk', max_age=3600)  # Pylons 0.9.7 syntax. 
    forward_to = request.headers.get('REFERER', '/')
    redirect_to(forward_to)

This sets a cookie 'sitelang' with string value 'uk' which expires in an hour (3600 seconds).

Cookies can be read from the dictionary 'cookies' of the global request object in the next
request.

1
lang = request.cookies['sitelang']

Site running on a free Atlassian Confluence Open Source Project License granted to Pylons. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.3 Build:#645 Feb 13, 2007) - Bug/feature request - Contact Administrators
Top