一、cookie簡介html
1. cookie實質就是客戶端硬盤中存放的鍵值對,利用這個特性能夠用來作用戶驗證前端
2. 好比:{「username」: 「dachengzi」} #再次訪問url就會攜帶這些信息過來jquery
二、前端操做cookie
說明: 使用下面方法操cookie必須先引入jquery.cookie.jsdjango
1. 前端獲取cookie值: var v = $.cookie('per_page_count');後端
2. 前端設置cookie值: $.cookie('per_page_count',v);cookie
三、後端操做cookieapp
說明: response = HttpResponse(...) 或 response = render(request, ...)ide
1. 後端設置cookie值: response.set_cookie('username',"zhangsan")url
2. 後端後去cookie值: request.COOKIES.get('username')spa
四、使用cookie實現用戶登陸、註銷
from django.contrib import admin from django.urls import path,re_path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'login/$',views.login), re_path(r'index/$',views.index), re_path(r'logout/$',views.logout), ]
from django.shortcuts import render,HttpResponse,redirect def index(request): username = request.COOKIES.get('username') # 獲取cookie if not username: return redirect('/login/') return HttpResponse(username) def login(request): if request.method == "GET": return render(request,'login.html',{'msg':''}) if request.method == "POST": u = request.POST.get('username') p = request.POST.get('pwd') print(u,p) if u == 'tom' and p == '123': res = redirect('/index/') res.set_cookie('username',u ,max_age=10) # 設置500s免登錄 return res else: return render(request,'login.html', {'msg':'用戶名或密碼錯誤'}) def logout(req): response = redirect('/login/') #清理cookie裏保存username response.delete_cookie('username') return response
<form action="/login/" method="POST"> <input type="text" name="username" placeholder="用戶名"> <input type="text" name="pwd" placeholder="密碼"> <input type="submit" value="提交"> <p>{{ msg }}</p> </form>