简体   繁体   中英

Issue with creating/retrieving cookies in Flask

When the class AnonUser is initialized, the code should check if a cookie exists and create a new one if it doesn't. The relevant code snippet is the following:

class AnonUser(object):
    """Anonymous/non-logged in user handling"""
    cookie_name = 'anon_user_v1'

    def __init__(self):
        self.cookie = request.cookies.get(self.cookie_name)
        if self.cookie:
            self.anon_id = verify_cookie(self.cookie)
        else:
            self.anon_id, self.cookie = create_signed_cookie()
            res = make_response()
            res.set_cookie(self.cookie_name, self.cookie)

For some reason, request.cookies.get(self.cookie_name) always returns None. Even if I log "request.cookies" immediately after res.set_cookie, the cookie is not there.

The strange thing is that this code works on another branch with identical code and, as far as I can tell, identical configuration settings (it's not impossible I'm missing something, but I've been searching for the past couple hours for any difference with no luck). The only thing different seems to be the domain.

Does anyone know why this might happen?

I figured out what the problem was. I was apparently wrong about it working on the other branch; for whatever reason it would work if the anonymous user already had some saved collections (what the cookies are used for), and I'm still not sure why that is, but the following ended up resolving the issue:

@app.after_request
def set_cookie(response):
    if not request.cookies.get(g.cookie_session.cookie_name):
        response.set_cookie(g.cookie_session.cookie_name, g.cookie_session.cookie)
    return response

The main things I needed to do were import "request" from flask and realize that I could reference the cookie and cookie name through just referring to the anonymous user ("cookie_session") class where they were set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM