Maa*_*aal 6 python cookies google-app-engine python-2.7
我正在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 Cache-Control:no-cache Set-Cookie:MyCookie = NewValue; 到期= 2012年12月6日星期四17:55:41 GMT; 路径= /内容长度:1199
上面的"无"是指代码中的"value1".
你能否告诉我为什么cookie值为"None",即使它被添加到标题中?
非常感激您的帮忙.
当您调用 时set_cookie(),它会在它准备的响应上设置 cookie(也就是说,它会在您的函数返回后发送响应时设置 cookie)。随后的调用get_cookie()是从当前请求的标头中读取。由于当前请求没有您正在测试的 cookie 集,因此不会被读入。但是,如果您要重新访问此页面,您应该会得到不同的结果,因为 cookie 现在将成为请求的一部分。
| 归档时间: | 
 | 
| 查看次数: | 4828 次 | 
| 最近记录: |