我正在通過使用Python和Google App Engine的Web應用程序開發的Udacity課程。在設置cookies(計數訪問者數量)和散列的課程中,我注意到一些令我困惑的事情:是否需要刷新瀏覽器才能看到新的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)。
什麼是困惑我的是,我還打印出cookie值後加1,它仍然打印「5」 - 儘管該cookie已經被重置爲6
這是爲什麼?瀏覽器需要在新的cookie正確讀取之前刷新或者什麼?
這裏是有問題的代碼: 類CookiePage(BlogHandler): DEF得到(個體): self.response.headers [ '內容 - 類型'] = 'text/plain的' 訪問= 0 visits_cookie_str = self.request.cookies.get( '訪問') 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
你是如何設置cookie的?通過Javascript或在服務器上?另外,你能告訴我們一些實際的代碼嗎? –
正在使用Python和Google App Engine進行設置。我將用代碼更新我的問題。 – BandfuzzAlex
查看我更新的答案。 –