2018/2/2 19:07:47当前位置推荐好文程序员浏览文章

1.简述

(1)设置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)检测Cookies
if "cookie_name" in request.COOKIES :
(5)response.set_cookie() 传递一些可选的参数 描述

2.示例

2.1设置Cookies

login_user = models.User.objects.get(username=username, password=password) # 这里用的mongodb进行的数据存储# print(login_user["username"])# 帐号和密码正确,cookie保存登录状态# 获取相应对象response = redirect(reverse("blog:index"))# 设置cookieresponse.set_cookie("blog_username", login_user["username"], 604800) #过期时间单位是s (这里设置为7天)response.set_cookie("blog_password", login_user["password"], 604800)

2.2检测、获取Cookies

def index(request):    # 检测cookies是否存在    if "blog_username" in request.COOKIES:        # 获取cookies        login_username = request.COOKIES.get("blog_username")        login_password = request.COOKIES.get("blog_password")        # 获取登录用户信息        login_user = models.User.objects.get(username=login_username, password=login_password)       # 返回登录成功后页面        return render(request, "blog/index.html", {"login_user": login_user})    else:        # 进入未登录状态的主页        return render(request, "blog/index.html")

2.3删除Cookies

# 注销登录视图函数def logout(request):    response = redirect(reverse("blog:index"))    response.delete_cookie("blog_username")    response.delete_cookie("blog_password")    return response
网友评论