原文:https://www.cnblogs.com/sss4/p/7071334.htmlcss
HTTP協議 是短鏈接、且狀態的,因此在客戶端向服務端發起請求後,服務端在響應頭 加入cokie響應給瀏覽器,以此記錄客戶端狀態;
html
cook是來自服務端,保存在瀏覽器的鍵值對,主要應用於用戶登陸;瀏覽器
cookie如此重要!!那麼如何在Django應用cookie呢?cookie又有什麼缺陷呢?安全
一、max_age=1 :cookie生效的時間,單位是秒cookie
二、expires:具體過時日期 dom
三、path='/':指定那個url能夠訪問到cookie;‘/’是全部; path='/'ide
四、 domain=None(None表明當前域名):指定那個域名以及它下面的二級域名(子域名)能夠訪問這個cookie函數
五、secure=False:https安全相關post
六、httponly=False:限制只能經過http傳輸,JS沒法在傳輸中獲取和修改ui
1.普通
obj.set_cookie("tile","zhanggen",expires=value,path='/' )
2.加鹽
普通cookie是明文傳輸的,能夠直接在客戶端直接打開,因此須要加鹽,解鹽以後才能查看
一、普通
request.COOKIES.get(‘k’)
二、加鹽
cookies=request.get_signed_cookie('k',salt='zhanggen')
1.簡單應用:longin界面和index界面,訪問index界面先判斷是否登陸,若登陸能夠訪問,若未登陸跳轉到登陸界面。
【代碼】
#settings.py文件 :設置靜態文件路徑,將css樣式放到該路徑中 STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) #urls.py文件:設置url路由 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^identify/', views.identify), url(r'^login/', views.login), url(r'^index/', views.index), ] #views.py文件 def login(request): if request.method == "GET": return render(request,'login.html',{'msg':''}) elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username == 'lijun25' and password == 'lijun25': obj = redirect('/index/') obj.set_cookie('1234567',username,max_age=10) return obj else: return render(request, 'login.html',{'msg':'用戶名或密碼錯誤'}) def index(request):
v = request.COOKIES.get('1234567') print v if v: return render(request, 'index.html') else: return redirect('/login/')
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-Control" content="no-cache"> <meta http-equiv="Expires" content="0"> <title>後臺管理</title> <link href="/static/login.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="login_box"> <div class="login_l_img"><img src="/static/images/login-img.png" /></div> <div class="login"> <div class="login_logo"><a href="#"><img src="/static/images/login_logo.png" /></a></div> <div class="login_name"> <p>後臺管理系統</p> </div> <form method="post"> <input name="username" type="text" value="用戶名" onfocus="this.value=''" onblur="if(this.value==''){this.value='用戶名'}"> <span id="password_text" onclick="this.style.display='none';document.getElementById('password').style.display='block';document.getElementById('password').focus().select();" >密碼</span> <input name="password" type="password" id="password" style="display:none;" onblur="if(this.value==''){document.getElementById('password_text').style.display='block';this.style.display='none'};"/> <input value="登陸" style="width:100%;" type="submit"> <div color="red" align="center">{{ msg }}</div> </form> </div> </div> <div style="text-align:center;"> </div> </body> </html>
【驗證】
登陸成功後能夠看到瀏覽器上的定義的一對鍵值,會跳轉到index頁面,過10s鍾後再cookies會失效,刷新會返回到登陸界面從新認證
2.進階應用:以上這樣cookies是明文的,很不安全
#views.py def login(request): if request.method == "GET": return render(request,'login.html',{'msg':''}) elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username == 'lijun25' and password == 'lijun25': obj = redirect('/index/') # obj.set_cookie('k',username,max_age=10,) obj.set_signed_cookie('k','v',salt='auto',max_age=10) return obj else: return render(request, 'login.html',{'msg':'用戶名或密碼錯誤'}) def index(request):
# cookie = request.COOKIES.get('k')
try:
cookie = request.get_signed_cookie('k',salt='auto')
print cookie
return render(request, 'index.html')
except:
return redirect('/login/')
【驗證】
第一次訪問Djanao程序會給瀏覽器一對鍵值對(Response Cookies),是加鹽的,在一次訪問Request Cookies裏會帶着這對鍵值對給Django程序。
3.繼續進階應用,若views函數後續持續增長,那麼就須要在每一個視圖函數前加入cookie認證,代碼重複,在不修改源代碼和不修改調用方式的前提下,這時候就須要用裝飾器了
def cookie_auth(func): def weaper(request,*args,**kwargs): #cookies = request.get_signed_cookie('k', salt='zhanggen') try: cookie = request.get_signed_cookie('k', salt='auto') print cookie if cookie == 'v': return func(request) else: return redirect('/login/') except: return redirect('/login/') return weaper def login(request): if request.method == "GET": return render(request,'login.html',{'msg':''}) elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username == 'lijun25' and password == 'lijun25': obj = redirect('/index/') # obj.set_cookie('k',username,max_age=10,) obj.set_signed_cookie('k','v',salt='auto',max_age=10) return obj else: return render(request, 'login.html',{'msg':'用戶名或密碼錯誤'}) @cookie_auth def home(request): return HttpResponse('歡迎來得home界面') @cookie_auth def index(request): return render(request, 'index.html')