使用Python和Google App Engine制作Cookies

6

我正在Google App Engine上开发一个应用程序,遇到了一个问题。我想为每个用户会话添加一个cookie,以便能够区分当前的用户。我希望他们都是匿名的,因此我不想要登录。因此,我已经实现了以下cookie代码。

def clear_cookie(self,name,path="/",domain=None):
    """Deletes the cookie with the given name."""
    expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
    self.set_cookie(name,value="",path=path,expires=expires,
                    domain=domain)    

def clear_all_cookies(self):
    """Deletes all the cookies the user sent with this request."""
    for name in self.cookies.iterkeys():
        self.clear_cookie(name)            

def get_cookie(self,name,default=None):
    """Gets the value of the cookie with the given name,else default."""
    if name in self.request.cookies:
        return self.request.cookies[name]
    return default

def set_cookie(self,name,value,domain=None,expires=None,path="/",expires_days=None):
    """Sets the given cookie name/value with the given options."""

    name = _utf8(name)
    value = _utf8(value)
    if re.search(r"[\x00-\x20]",name + value): # Don't let us accidentally inject bad stuff
        raise ValueError("Invalid cookie %r:%r" % (name,value))
    new_cookie = Cookie.BaseCookie()
    new_cookie[name] = value
    if domain:
        new_cookie[name]["domain"] = domain
    if expires_days is not None and not expires:
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
    if expires:
        timestamp = calendar.timegm(expires.utctimetuple())
        new_cookie[name]["expires"] = email.utils.formatdate(timestamp,localtime=False,usegmt=True)
    if path:
        new_cookie[name]["path"] = path
    for morsel in new_cookie.values():
        self.response.headers.add_header('Set-Cookie',morsel.OutputString(None))

为了测试上述代码,我使用了以下代码:
class HomeHandler(webapp.RequestHandler):
    def get(self):
        self.set_cookie(name="MyCookie",value="NewValue",expires_days=10)
        value1 = str(self.get_cookie('MyCookie'))    
        print value1

当我运行这个代码时,HTML文件中的标题如下所示:

None 状态: 200 OK 内容类型: text/html; charset=utf-8 缓存控制: no-cache 设置Cookie: MyCookie=NewValue; expires=Thu, 06 Dec 2012 17:55:41 GMT; Path=/ 内容长度: 1199

以上的 "None" 指的是代码中的 "value1"。
请问为什么即使将 Cookie 添加到标题中,其值仍为 "None"?
非常感谢您的帮助。
1个回答

5
当您调用 set_cookie() 时,它会在准备的响应上设置 cookie(也就是说,在函数返回后发送响应时设置 cookie)。后续调用 get_cookie() 是从当前请求头中读取的。由于当前请求没有设置您正在测试的 cookie,因此不会被读取。但是,如果您重新访问此页面,则应该会得到不同的结果,因为 cookie 现在将成为该请求的一部分。

非常感谢您的回答,但很遗憾当我重新访问页面时并没有得到不同的结果。我愿意听取其他建议。 - Maal
抱歉,我刚刚意识到你是100%正确的。非常感谢你。 - Maal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接