Python之路66-Django中的Cookie和Session
阿新 • • 發佈:2017-05-26
python
目錄
一、Cookie
二、Session
一、Cookie
1.獲取Cookie
request.COOKIES["key"] request.get_signed_cookie(key, default=RAISE_ERROR, s, max_age=None) # 參數 # default:默認值 # salt:加密鹽 # max_age:後臺控制過期時間
2.設置Cookie
rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key, value, ...) rep.set_signed_cookie(key, value, salt="加密鹽", ...) # 如果只有key、value默認關閉瀏覽器後cookie就失效了,這裏可以設置以下一些參數來自定義 # 參數 # key, 鍵 # value="", 值 # max_age=None, 超時時間,默認秒 # expires=None, 超時時間,到什麽時候截止 # path="/", Cookie生效的路徑,/表示跟路徑,特殊的:跟路徑的cookie可以被任何url的頁面訪問 # domain=None, Cookie生效的域名 # secure=False, https傳輸 # httponly=False, 只能http協議傳輸,無法被JavaScript獲取(不是絕對,底層抓包可以獲取到也可以被覆蓋)
由於cookie保存在客戶端的電腦上,所以,JavaScript和jQuery也可以操作cookie
<script src="/static/js/jquery.cookie.js"></script> $.cookie("list_pager_num", 30, {path:"/"});
通過cookie來實現用戶登錄
urls.py
from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/‘, views.login), url(r‘^index/‘, views.index), ]
views.py
user_info = { "dachengzi" : {"pwd": "123123"}, "kangbazi": {"pwd": "kkkkkk"}, } def login(request): if request.method == "GET": return render(request, "login.html") if request.method == "POST": u = request.POST.get("username") p = request.POST.get("password") dic = user_info.get(u) if not dic: return render(request, "login.html") if dic["pwd"] == p: res = redirect("/index/") res.set_cookie("username", u) return res else: return render(request, "login.html") def index(request): # 獲取當前已經登錄的用戶名 v = request.COOKIES.get("username") if not v: return redirect("/login") return render(request, "index.html", {"current_user": v})
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="username" placeholder="用戶名"/> <input type="password" name="password" placeholder="密碼"/> <input type="submit" /> </form> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>歡迎登錄,{{ current_user }}</h1> </body> </html>
通過cookie實現定制顯示數據條目
這裏引入了一個jQuery的插件
jquery.cookie.js
操作
<!--設置cookie--> $.cookie("per_page_count", v, {path: "/user_list/"}); <!--獲取cookie--> $.cookie("per_page_count");
urls.py
from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^user_list/‘, views.user_list), ]
views.py
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. from django.urls import reverse from utils import pagination LIST = [] for i in range(1009): LIST.append(i) def user_list(request): current_page = request.GET.get("p", 1) current_page = int(current_page) val = request.COOKIES.get("per_page_count") print(val) if val: val = int(val) page_obj = pagination.Page(current_page, len(LIST), val) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") return render(request, "user_list.html", {"li": data, "page_str": page_str}) else: page_obj = pagination.Page(current_page, len(LIST)) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") rep = render(request, "user_list.html", {"li": data, "page_str": page_str}) rep.set_cookie("per_page_count", "10", path="/user_list/") return rep
user_list.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pagination .page{ display: inline-block; padding: 5px; background-color: cyan; margin: 5px; } .pagination .page.active{ background-color: brown; color: black; } </style> </head> <body> <ul> {% for item in li %} {% include "li.html" %} {% endfor %} </ul> <div> <select id="px" onchange="changePageSize(this);"> <option value="10">10</option> <option value="30">30</option> <option value="50">50</option> <option value="100">100</option> </select> </div> <div class="pagination"> {{ page_str }} </div> <script src="/static/jquery-1.12.4.js"></script> <script src="/static/jquery.cookie.js"></script> <script> $(function () { var v = $.cookie("per_page_count"); $("#px").val(v); }); function changePageSize(ths) { var v = $(ths).val(); $.cookie("per_page_count", v, {path: "/user_list/"}); location.reload(); } </script> </body> </html>
本文出自 “八英裏” 博客,請務必保留此出處http://5921271.blog.51cto.com/5911271/1929633
Python之路66-Django中的Cookie和Session