2012-11-26 115 views
5

我正在Google App Engine上开发应用程序,并遇到问题。我想为每个用户会话添加一个cookie,以便我能够区分当前用户。我希望他们都是匿名的,因此我不想登录。因此,我已经实施了以下Cookie代码。使用Python和Google App Engine的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 Content-Type:text/html; charset = utf-8 Cache-Control:no-cache Set-Cookie:MyCookie = NewValue; expires =星期四,2012年12月06日17:55:41 GMT; Path =/ 内容长度:1199

上面的“无”代表代码中的“value1”。

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

非常感谢您的帮助。

回答

3

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

+0

非常感谢您的回答,但不幸的是,我在重访该页面时没有得到不同的结果。我打开其他建议? – Maal

+0

对不起。我只是意识到你是100%正确的。非常感谢你。 – Maal