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

2020-02-26 07:14发布

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.

标签: plone zope
2条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-26 07:32

To set cookies you use RESPONSE.setCookie.

>>> self.REQUEST.RESPONSE.setCookie('cookiename', 'cookievalue', expires='Wed, 22 June 2009 12:00:00 GMT')

The cookie will end up in the REQUEST in the next request.

>>> self.REQUEST['cookiename']
'cookievalue'

You "delete" the cookie by using None as a value.

**Note, though, that most of the times when people use cookies it's to store variables that have to do with sessions, and you can use self.REQUEST.SESSION for that, it's easier.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-26 07:50

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.

查看更多
登录 后发表回答