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 文件中的标题如下所示:

无状态:200 OK 内容类型:text/html;charset=utf-8 缓存控制:无缓存 Set-Cookie:MyCookie=NewValue;到期=格林威治标准时间 2012 年 12 月 6 日星期四 17:55:41;路径=/内容长度:1199

上面的“None”是指代码中的“value1”。

你能告诉我为什么cookie值是“无”,即使它被添加到标题中?

非常感激您的帮忙。

4

1 回答 1

5

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

于 2012-11-26T18:35:39.033 回答