Creating cookie if not present and modify it if present

20 views
Skip to first unread message

Jon Subscripted

unread,
Apr 18, 2020, 2:33:58 PM4/18/20
to web...@googlegroups.com
Hi everyone,
I'm facing some problems handling cookies. I need to store and update a value for non-auth users.
I need to do it throughout the session (this could be done with session cookies) but also between different sessions. That's why I decided to use cookies.

I tried to follow web2py books' instructions ( http://www.web2py.com/books/default/chapter/29/04/the-core#Cookies ), but it does not work as expected.

My problem is that I just succeed to set the cookie value properly the first time. My guess is that I do not fully understand the request/response

````
if not request.cookies.has_key('elocookie'):
    logger.debug("create ELO cookie")
    response.cookies['elocookie'] = (MU,PHI,SIGMA)
    response.cookies['elocookie']['expires'] = 72 * 3600
    response.cookies['elocookie']['path'] = '/'
else:
    value = request.cookies['elocookie'].value
    logger.debug('read ELO cookie %s'%str(value))
    mu,phi,sigma = [float(v) for v in value.replace('(','').replace(')','').split(',')]


logger.debug("retrieved elo %s %s %s"%(mu,phi,sigma))
... #calculate mu,phi,sigma

response.cookies['elocookie'] = (mu,phi,sigma)

logger.debug("new cookie elo %s %s %s"%(mu,phi,sigma))
````

Could anyone tell me what I missed or misunderstood?
Thanks, Jon.

Jon Subscripted

unread,
Apr 19, 2020, 3:59:15 AM4/19/20
to web...@googlegroups.com
Hi everyone,
I figured out what I was doing wrong. From what I can see you need to "fully create" the response cookie whenever you want to overwrite the values you read from request cookie.

So I modified my code as follows and it worked:

if not request.cookies.has_key('elocookie'):
    mu = MU
    phi = PHI
    sigma = SIGMA

else:
    value = request.cookies['elocookie'].value
    logger.debug('read ELO cookie %s'%str(value))
    mu,phi,sigma = [float(v) for v in value.replace('(','').replace(')','').split(',')]


logger.debug("retrieved elo %s %s %s"%(mu,phi,sigma))

... #calculate mu,phi,sigma

response.cookies['elocookie'] = (mu,phi,sigma)
response.cookies['elocookie']['expires'] = 72 * 3600
response.cookies['elocookie']['path'] = '/'
logger.debug("new cookie elo %s %s %s"%(mu,phi,sigma))

Thanks, Jon.
Reply all
Reply to author
Forward
0 new messages