How do you get and set cookies in Zope and Plone?

plone, zope

Solution

Use the `response.setCookie()` method. You can reach the response object via the request object. The latter you can reach via acquisition (`self.REQUEST`), or in views by accessing the passed-in request object, usually via `self.request`:

self.request.response.setCookie(name, value, **options)

where `options` end up as extra cookie parameters. Thus, turning a cookie into a non-session cookie requires a `expires='date'` keyword, limiting the cookie to a path is a `path='/somepath'` keyword to the `setCookie()` method. The usual browser cookie rules apply here.

To expire a cookie already set in the browser, you could either use a `expires='date in the past'` keyword, or you could use the `response.expireCookie()` method, which does this for you:

self.request.response.expireCookie(name, **options)

In this case you can still include options like the `path` or other cookie flags, but the method will override the `max_age` and `expires` options to ensure the cookie is deleted by the browser.

Although you could use Zope's `SESSION` support, you really need to think through the scalability issues. For example, you need to think through how session data will be shared across a cluster if you use ZEO or RelStorage. It is generally preferable to avoid using `SESSION` altogether if scalability is going to be an issue.

Problem

Documentation, and more importantly, some code examples would be very useful. I would prefer this to not be in protected scripts, but in the code that goes into modern packages.

Original source