[mod_python] SOLVED + example: Cookie setting and reading

Deleersnyder, Sebastien sebastien.deleersnyder at be.unisys.com
Sat Sep 1 08:57:32 EST 2001


Hi,

After some checking and aid from Leonid Timochouk I solved the problem.
I already had a send_http_header() call before my cookie setting 
(classic mistake).
The cookie is send to the server as part of the headers_in.

Here is my sample code:

<snip>
from mod_python import apache,
def getCookie(headers_in, key):
    """ Method to retrieve a certain cookie, returns None if not found, or
not set"""
    if headers_in.has_key('Cookie'):
        import Cookie
        C = Cookie.SmartCookie(headers_in['Cookie'])
        C.load(headers_in['Cookie'])
        if C.has_key(key):
            return C[key].value
    return None

def handler(req):
    """ This sample code will result in 'None' the first time the page is
leaded
    and 'Value' on the reload."""
    form = util.FieldStorage(req)
    req.headers_out['Set-Cookie']='key=value; path=/; expires=Wed,
09-Nov-2030 23:59:00 GMT'
    req.write(repr(getCookie(req.headers_in, 'key')))
    return apache.OK
</snip>

regards,

Sebastien
>  -----Original Message-----
> From: 	Deleersnyder, Sebastien  
> Sent:	zaterdag 1 september 2001 12:21
> To:	mod_python at modpython.org
> Subject:	Cookie setting and reading
> 
> Hi,
> 
> This certainly has been discussed here before, but I do not seem to find 
> any documentation/example on the following.
> 
> How do I set a cookie. And how do I read the same cookie back?
> 
> I think the following code should set the cookie and forces the browser to
> save 
> the cookie for a next logon (by setting the expiration date to the
> maximum).
> 
> req.headers_out['Set-Cookie']='key=value; path=/; expires=Wed, 09-Nov-2030
> 23:59:00 GMT'
> req.send_http_header()
> 
> Only I am testing this with IE 6 and I do not see the cookie in my cookie
> directory or privacy settings.
> My privacy settings is configured to allow all cookies.
> 
> Next question:
> If successfully set, how do I read the cookie when the client reconnects?
> Is this a member of the request class?
> 
> regards,
> 
> Sebastien



More information about the Mod_python mailing list