[Zope] Set and Detect Cookies in same call?

Casey Duncan casey@zope.com
Mon, 21 Oct 2002 13:43:22 -0400


The call to "setCookie" merely changes the cookies HTTP header that is sent to the user agent (browser). It suggests to the browser that is should persist this value and send it back with any and all requests in the domain (and path) of the cookie. 

Whether the user agent actually does this is not knowable until the next request when the cookie comes back (or doesn't).

cookies.has_key reflects all cookie values from the user agent plus any that have been set in this request AFAIK. So your diagnosis is correct, it is not telling you that the user agent has actually "eaten" the cookie. It hasn't even gotten to the user agent yet. That doesn't happen until you start sending data to the user agent.

So the only way to see if cookies are enabled it to try to set one in one request and then try to read it in another. If it isn't there, then you know cookies are not supported by the user agent.

The best way to do this is to set the cookie and redirect the browser to get another URL which looks for the cookie. Something like:

## Script (Python) "testSetCookie"
response = context.REQUEST.RESPONSE
response.setCookie('foo', 'Some Value', path='/')
response.redirect('testGetCookie')

## Script (Python) "testGetCookie"
response = context.REQUEST.RESPONSE
if response.cookies.has_key('foo'):
    # We have cookies, be happy

hth,

-Casey
 

On Mon, 21 Oct 2002 13:17:48 -0400
"Jim Kutter" <zope-list@ebizq.net> wrote:

> I have searched high and low for an answer, and haven't found one yet:
> 
> Is it possible to set a cookie, then detect if it got set properly immediately after? Or do I have to set it in one call, then detect it in another?
> 
> It seems that setCookie puts the "cookie" variable into the request object regardless if cookies are enabled, so a later in the same call, calling cookies.has_key always returns true. Is this what's happening?
> 
> Thanks
> 
> -jim