Tôi đang phát triển một ứng dụng trên Google App Engine và đã gặp sự cố. Tôi muốn thêm cookie vào mỗi phiên người dùng để tôi có thể phân biệt giữa những người dùng hiện tại. Tôi muốn tất cả chúng được ẩn danh, vì vậy tôi không muốn đăng nhập. Tôi đã triển khai mã sau cho cookie.Cookie sử dụng Python và Google App Engine
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))
Để kiểm tra mã trên tôi đã sử dụng đoạn mã sau:
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
Khi tôi chạy tiêu đề trong file HTML trông như sau:
Không Status : 200 OK Loại nội dung: văn bản/html; charset = utf-8 Bộ nhớ cache-Điều khiển: no-cache Đặt cookie: MyCookie = NewValue; hết hạn = Thu, 06/12/2012 17:55:41 GMT; Đường dẫn =/ Độ dài nội dung: 1199
"Ở trên đề cập đến" giá trị1 "từ mã.
Bạn có thể cho tôi biết lý do tại sao giá trị cookie là "Không", ngay cả khi nó được thêm vào tiêu đề?
Trợ giúp của bạn được đánh giá rất nhiều.
Cảm ơn bạn rất nhiều vì đã trả lời, nhưng tiếc là tôi không nhận được kết quả khác khi xem lại trang. Tôi mở cho các đề xuất khác? – Maal
Xin lỗi. Tôi chỉ nhận ra rằng bạn đúng 100%. Cảm ơn nhiều. – Maal