1.簡(jiǎn)述
(1)設(shè)置Cookies
response.set_cookie("cookie_key","value")
(2)獲取Cookies
value = request.COOKIES["cookie_key"]
(3)刪除Cookies
response.delete_cookie("cookie_key",path="/",domain=name)
(4)檢測(cè)Cookies
if "cookie_name" in request.COOKIES :
(5)response.set_cookie() 傳遞一些可選的參數(shù) 描述
2.示例
2.1設(shè)置Cookies
login_user = models.User.objects.get(username=username, password=password) # 這里用的mongodb進(jìn)行的數(shù)據(jù)存儲(chǔ)
# print(login_user["username"])
# 帳號(hào)和密碼正確,cookie保存登錄狀態(tài)
# 獲取相應(yīng)對(duì)象
response = redirect(reverse("blog:index"))
# 設(shè)置cookie
response.set_cookie("blog_username", login_user["username"], 604800) #過(guò)期時(shí)間單位是s (這里設(shè)置為7天)
response.set_cookie("blog_password", login_user["password"], 604800)
2.2檢測(cè)芝硬、獲取Cookies
def index(request):
# 檢測(cè)cookies是否存在
if "blog_username" in request.COOKIES:
# 獲取cookies
login_username = request.COOKIES.get("blog_username")
login_password = request.COOKIES.get("blog_password")
# 獲取登錄用戶(hù)信息
login_user = models.User.objects.get(username=login_username, password=login_password)
# 返回登錄成功后頁(yè)面
return render(request, "blog/index.html", {"login_user": login_user})
else:
# 進(jìn)入未登錄狀態(tài)的主頁(yè)
return render(request, "blog/index.html")
2.3刪除Cookies
# 注銷(xiāo)登錄視圖函數(shù)
def logout(request):
response = redirect(reverse("blog:index"))
response.delete_cookie("blog_username")
response.delete_cookie("blog_password")
return response