我正在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" 指的是代码中的 "value1"。None 状态: 200 OK 内容类型: text/html; charset=utf-8 缓存控制: no-cache 设置Cookie: MyCookie=NewValue; expires=Thu, 06 Dec 2012 17:55:41 GMT; Path=/ 内容长度: 1199
请问为什么即使将 Cookie 添加到标题中,其值仍为 "None"?
非常感谢您的帮助。