Question

I am trying to figure out how cookies work in a Python Bottle application. Please be kind as I am pretty new to Python. How do I read a value out of the cookie that I have set?

Example:

@route('/cookie_setpage/')
def settingcookie():
    response.set_cookie('Cookie_name','Some value')
    return 'Set!'

@route('/cookie_readpage/')
def testingcookie():
    r=request.get_cookie('Cookie_name')
    return str(r)

When I do this I get the text "None" as return, which seems to be the default value or something. How am I suppose to access the text 'Some value' from the cookie got with get_cookie?

Was it helpful?

Solution

Your solution

bottle does not send a path along with the cookie if you don't specify it, which means that the browser is in charge of deciding which path to use for the cookie (for some reason, the bottle docs state something else).

(If you don't know what the path is, read the other title in this answer).

RFC 2109 (search for "Interpreting Set-Cookie") states that the default path for a Cookie is the path that generated the cookie/cookie_setpage, in your case.

This of course means the cookie is not being sent to /cookie_readpage.

To solve that, just define a path when you set the cookie:

response.set_cookie('Cookie_name','Some value', path='/')  # Your entire site.

What is cookie path?

The path is an attribute of the cookie.

The browser will only send a cookie to pages that are "below" the path for the cookie.

So, if you set your cookie path to /cookie_setpage, then /cookie_setpage/cookie_readpage gets the cookie, but /cookie_readpage doesn't.

if you set it to /, then any page gets it, because it's your site's root.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top