我正在学习使用 Python 和 Google App Engine 开发网络应用程序的 Udacity 课程。在设置 cookie(计算访问者数量)和散列的课程中,我注意到一些让我感到困惑的事情:
为了好玩,我决定在添加 1 次访问之前和之后打印出“访问”的 cookie 值。这是输出:
5|e4da3b7fbbce2345d7772b0674a318d5 [[[this is cookie before adding 1 to it]]
You've been here 6 times! [[this is printed after adding 1 to cookie, but is not the cookie]]
5|e4da3b7fbbce2345d7772b0674a318d5 [[this is printing the cookie after one has been set using "Set-Cookie"]]
中间的6是正确的。使用 cookie 查看器,我已验证它与 cookie 匹配。所以第一行中的“5”也是正确的(因为这一行是在添加1之前读取cookie)。
令我困惑的是,我还在加 1 后打印出 cookie 值,它仍然打印“5”——即使 cookie 已经重置为 6。
这是为什么?在正确读取新cookie之前是否需要刷新浏览器?
这是有问题的代码: class CookiePage(BlogHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' visit = 0 visit_cookie_str = self.request.cookies.get( 'visits') self.write(visits_cookie_str) # 这是第一行打印 self.write("\n")
if visits_cookie_str:
cookie_val = check_secure_val(visits_cookie_str)
visits = int(cookie_val)
visits += 1
new_cookie_val = make_secure_val(str(visits))
self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)
self.write("You've been here %s times!\n" % visits) # this is the 2nd line printed
cookie = self.request.cookies.get('visits')
self.write(cookie) # this is the 3rd line printed which SHOULD match the one above it but doesn't