分页和Cookie、Session
分页
自定义分页
from django.shortcuts import render # Create your views here. data = [] for i in range(1, 302): tmp = {"id": i, "name": "alex-{}".format(i)} data.append(tmp) # data def user_list(request): try: page_num = int(request.GET.get("page")) # 字符串类型,所以要转成int except Exception as e: page_num = 1 # 没有传页码, 默认展示第一页 # if not page_num: # page_num = 1 # 每一页显示10条记录 per_page_num = 10 # user_list = data[0:10] 1 (1-1) *10 1*10 # user_list = data[10:20] 2 (2-1) *10 2*10 # user_list = data[20:30] 3 (n-1)*10 n*10 # 总数据个数 total_count = len(data) # 总共有多少页 total_page_num, more = divmod(total_count, per_page_num) if more: total_page_num += 1 # 如果你输入的页码数超过我的总页数,我默认返回最后一页 if page_num > total_page_num: page_num = total_page_num # 最多显示多少页码 max_show = 11 half_show = int((max_show-1)/2) # 页面上页码从哪儿开始 page_start = page_num - half_show # 页面上页码最多展示到哪一个 page_end = page_num + half_show # 如果当前页小于等于half_show, 默认从第一页展示到max_show if page_num <= half_show: page_start = 1 page_end = max_show # 如果当前页大于等于总页数-half_show if page_num >= total_page_num - half_show: page_end = total_page_num page_start = total_page_num - max_show # 生成前页码的HTML page_html_list = [] # 放置一个首页按钮 page_first_tmp = '<li><a href="/user_list/?page=1">首页</a></li>' page_html_list.append(page_first_tmp) # 加上一页按钮 if page_num - 1 <= 0: # 表示没有上一页 page_prev_tmp = '<li class="disabled" ><a href="#">上一页</a></li>' else: page_prev_tmp = '<li><a href="/user_list/?page={}">上一页</a></li>'.format(page_num - 1) page_html_list.append(page_prev_tmp) for i in range(page_start, page_end+1): # 如果是当前页,就加一个active的样式 if i == page_num: tmp = '<li class="active"><a href="/user_list/?page={0}">{0}</a></li>'.format(i) else: tmp = '<li><a href="/user_list/?page={0}">{0}</a></li>'.format(i) page_html_list.append(tmp) # 加下一页按钮 if page_num+1 > total_page_num: page_next_tmp = '<li class="disabled"><a href="#">下一页</a></li>' else: page_next_tmp = '<li><a href="/user_list/?page={}">下一页</a></li>'.format(page_num+1) page_html_list.append(page_next_tmp) # 添加一个尾页 page_last_tmp = '<li><a href="/user_list/?page={}">尾页</a></li>'.format(total_page_num) page_html_list.append(page_last_tmp) page_html = "".join(page_html_list) # 去数据库取数据 start = (page_num - 1) * per_page_num end = page_num * per_page_num user_list = data[start:end] return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})
""" 这个文件的使用指南 """ class MyPage(object): def __init__(self, page_num, total_count, base_url, per_page_num=10, max_show=11): """ :param page_num: 当前页 :param total_count: 数据总个数 :param base_url: 分页页码跳转的URL :param per_page_num: 每一页显示多少条数据 :param max_show: 页面上最多显示多少页码 """ # 实例化时传进来的参数 try: self.page_num = int(page_num) # 字符串类型,所以要转成int except Exception as e: self.page_num = 1 self.total_count = total_count self.base_url = base_url self.per_page_num = per_page_num self.max_show = max_show # 根据传进来的参数,计算的几个值 self.half_show = int((self.max_show - 1) / 2) # 总共有多少页 self.total_page_num, more = divmod(self.total_count, self.per_page_num) if more: self.total_page_num += 1 @property def start(self): return (self.page_num - 1) * self.per_page_num @property def end(self): return self.page_num * self.per_page_num def page_html(self): """ 返回页面上可以用的一段HTML 一段可用的分页页码的HTML :return: """ # 页面上页码从哪儿开始 page_start = self.page_num - self.half_show # 页面上页码最多展示到哪一个 page_end = self.page_num + self.half_show # 如果当前页小于等于half_show, 默认从第一页展示到max_show if self.page_num <= self.half_show: page_start = 1 page_end = self.max_show # 如果当前页大于等于总页数-half_show if self.page_num >= self.total_page_num - self.half_show: page_end = self.total_page_num page_start = self.total_page_num - self.max_show # 生成前页码的HTML page_html_list = [] # 放置一个首页按钮 page_first_tmp = '<li><a href="{}?page=1">首页</a></li>'.format( self.base_url) page_html_list.append(page_first_tmp) # 加上一页按钮 if self.page_num - 1 <= 0: # 表示没有上一页 page_prev_tmp = '<li class="disabled" ><a href="#">上一页</a></li>' else: page_prev_tmp = '<li><a href="{0}?page={1}">上一页</a></li>'.format( self.base_url, self.page_num - 1) page_html_list.append(page_prev_tmp) for i in range(page_start, page_end+1): # 如果是当前页,就加一个active的样式 if i == self.page_num: tmp = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format( self.base_url, i) else: tmp = '<li><a href="{0}?page={1}">{1}</a></li>'.format( self.base_url, i) page_html_list.append(tmp) # 加下一页按钮 if self.page_num+1 > self.total_page_num: page_next_tmp = '<li class="disabled"><a href="#">下一页</a></li>' else: page_next_tmp = '<li><a href="{0}?page={1}">下一页</a></li>'.format( self.base_url, self.page_num+1) page_html_list.append(page_next_tmp) # 添加一个尾页 page_last_tmp = '<li><a href="{0}?page={1}">尾页</a></li>'.format( self.base_url, self.total_page_num) page_html_list.append(page_last_tmp) return "".join(page_html_list)
def user_list(request): page_num = request.GET.get("page") path = request.path_info # request.get_full_path() # 带参数的URL from tools.mypage import MyPage page = MyPage(page_num, len(data), path) page_html = page.page_html() return render(request, "user_list.html", {"user_list": data[page.start:page.end], "page_html": page_html})
{% load static %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static "bootstrap-3.3.7/css/bootstrap.min.css" %}"> <title>用户列表</title> </head> <body> <div class="container"> <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>姓名</th> </tr> </thead> <tbody> {% for user in user_list %} <tr> <td>{{ user.id }}</td> <td>{{ user.name }}</td> </tr> {% endfor %} </tbody> </table> <div class="pull-right"> <nav aria-label="Page navigation"> <ul class="pagination"> {# {% for i in total_page_num %}#} {# <li><a href="/user_list/?page={{ i }}">{{ i }}</a></li>#} {# {% endfor %}#} {{ page_html|safe }} </ul> </nav> </div> </div> <script src="{% static "jquery-3.2.1.min.js" %}"></script> <script src="{% static "bootstrap-3.3.7/js/bootstrap.min.js" %}"></script> </body> </html>
yuan版
""" 分页组件使用示例: obj = Pagination(request.GET.get('page',1),len(USER_LIST),request.path_info) page_user_list = USER_LIST[obj.start:obj.end] page_html = obj.page_html() return render(request,'index.html',{'users':page_user_list,'page_html':page_html}) """ class Pagination(object): def __init__(self,current_page,all_count,base_url,per_page_num=2,pager_count=11): """ 封装分页相关数据 :param current_page: 当前页 :param all_count: 数据库中的数据总条数 :param per_page_num: 每页显示的数据条数 :param base_url: 分页中显示的URL前缀 :param pager_count: 最多显示的页码个数 """ try: current_page = int(current_page) except Exception as e: current_page = 1 if current_page <1: current_page = 1 self.current_page = current_page self.all_count = all_count self.per_page_num = per_page_num self.base_url = base_url # 总页码 all_pager, tmp = divmod(all_count, per_page_num) if tmp: all_pager += 1 self.all_pager = all_pager self.pager_count = pager_count self.pager_count_half = int((pager_count - 1) / 2) @property def start(self): return (self.current_page - 1) * self.per_page_num @property def end(self): return self.current_page * self.per_page_num def page_html(self): # 如果总页码 < 11个: if self.all_pager <= self.pager_count: pager_start = 1 pager_end = self.all_pager + 1 # 总页码 > 11 else: # 当前页如果<=页面上最多显示11/2个页码 if self.current_page <= self.pager_count_half: pager_start = 1 pager_end = self.pager_count + 1 # 当前页大于5 else: # 页码翻到最后 if (self.current_page + self.pager_count_half) > self.all_pager: pager_end = self.all_pager + 1 pager_start = self.all_pager - self.pager_count + 1 else: pager_start = self.current_page - self.pager_count_half pager_end = self.current_page + self.pager_count_half + 1 page_html_list = [] first_page = '<li><a href="%s?page=%s">首页</a></li>' % (self.base_url,1,) page_html_list.append(first_page) if self.current_page <= 1: prev_page = '<li class="disabled"><a href="#">上一页</a></li>' else: prev_page = '<li><a href="%s?page=%s">上一页</a></li>' % (self.base_url,self.current_page - 1,) page_html_list.append(prev_page) for i in range(pager_start, pager_end): if i == self.current_page: temp = '<li class="active"><a href="%s?page=%s">%s</a></li>' % (self.base_url,i, i,) else: temp = '<li><a href="%s?page=%s">%s</a></li>' % (self.base_url,i, i,) page_html_list.append(temp) if self.current_page >= self.all_pager: next_page = '<li class="disabled"><a href="#">下一页</a></li>' else: next_page = '<li><a href="%s?page=%s">下一页</a></li>' % (self.base_url,self.current_page + 1,) page_html_list.append(next_page) last_page = '<li><a href="%s?page=%s">尾页</a></li>' % (self.base_url,self.all_pager,) page_html_list.append(last_page) return ''.join(page_html_list)
Django封装好的分页
>>> from django.core.paginator import Paginator >>> objects = ['john', 'paul', 'george', 'ringo'] >>> p = Paginator(objects, 2) >>> p.count #数据总数 4 >>> p.num_pages #总页数 2 >>> type(p.page_range) # `<type 'rangeiterator'>` in Python 2. <class 'range_iterator'> >>> p.page_range #页码的列表 range(1, 3) # =========[1,2] >>> page1 = p.page(1) #第1页的page对象 >>> page1 <Page 1 of 2> >>> page1.object_list #第1页的数据 ['john', 'paul'] >>> page2 = p.page(2) >>> page2.object_list #第2页的数据 ['george', 'ringo'] >>> page2.has_next() #是否有下一页 False >>> page2.has_previous() #是否有上一页 True >>> page2.has_other_pages() #是否有其他页 True >>> page2.next_page_number() #下一页的页码 Traceback (most recent call last): ... EmptyPage: That page contains no results >>> page2.previous_page_number() #上一页的页码 1 >>> page2.start_index() # 本页第一条记录的序数(从1开始) 3 >>> page2.end_index() # 本页最后录一条记录的序数(从1开始) 4 >>> p.page(0) #错误的页,抛出异常 Traceback (most recent call last): ... EmptyPage: That page number is less than 1 >>> p.page(3) #错误的页,抛出异常 Traceback (most recent call last): ... EmptyPage: That page contains no results
Django内置分页
from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger L = [] for i in range(999): L.append(i) def index(request): current_page = request.GET.get('p') paginator = Paginator(L, 10) # per_page: 每页显示条目数量 # count: 数据总个数 # num_pages:总页数 # page_range:总页数的索引范围,如: (1,10),(1,200) # page: page对象 try: posts = paginator.page(current_page) # has_next 是否有下一页 # next_page_number 下一页页码 # has_previous 是否有上一页 # previous_page_number 上一页页码 # object_list 分页之后的数据列表 # number 当前页 # paginator paginator对象 except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'index.html', {'posts': posts})
实现分页的实例
前端部分
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'bootstrap.css' %}"> </head> <body> <div class="container"> <h4>分页器</h4> <ul> {% for book in book_list %} <li>{{ book.title }} {{ book.price }}</li> {% endfor %} </ul> <ul class="pagination" id="pager"> {% if book_list.has_previous %} <li class="previous"><a href="/blog/?page={{ book_list.previous_page_number }}">上一页</a></li> {% else %} <li class="previous disabled"><a href="#">上一页</a></li> {% endif %} {% for num in paginator.page_range %} {% if num == currentPage %} <li class="item active"><a href="/blog/?page={{ num }}">{{ num }}</a></li> {% else %} <li class="item"><a href="/blog/?page={{ num }}">{{ num }}</a></li> {% endif %} {% endfor %} {% if book_list.has_next %} <li class="next"><a href="/blog/?page={{ book_list.next_page_number }}">下一页</a></li> {% else %} <li class="next disabled"><a href="#">下一页</a></li> {% endif %} </ul> </div> </body> </html>
views视图函数
from django.shortcuts import render,HttpResponse # Create your views here. from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from app01.models import * def index(request): ''' 批量导入数据: Booklist=[] for i in range(100): Booklist.append(Book(title="book"+str(i),price=30+i*i)) Book.objects.bulk_create(Booklist) ''' book_list=Book.objects.all() paginator = Paginator(book_list, 10) page = request.GET.get('page',1) currentPage=int(page) try: print(page) book_list = paginator.page(page) except PageNotAnInteger: book_list = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) return render(request,"index.html",locals())
Cookie和Session
简介
1、cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞生。
cookie的工作原理是:由服务器产生内容,浏览器收到请求后保存在本地;当浏览器再次访问时,浏览器会自动带上cookie,这样服务器就能通过cookie的内容来判断这个是“谁”了。
2、cookie虽然在一定程度上解决了“保持状态”的需求,但是由于cookie本身最大支持4096字节,以及cookie本身保存在客户端,可能被拦截或窃取,因此就需要有一种新的东西,它能支持更多的字节,并且他保存在服务器,有较高的安全性。这就是session。
问题来了,基于http协议的无状态特征,服务器根本就不知道访问者是“谁”。那么上述的cookie就起到桥接的作用。
我们可以给每个客户端的cookie分配一个唯一的id,这样用户在访问时,通过cookie,服务器就知道来的人是“谁”。然后我们再根据不同的cookie的id,在服务器上保存一段时间的私密资料,如“账号密码”等等。
3、总结而言:cookie弥补了http无状态的不足,让服务器知道来的人是“谁”;但是cookie以文本的形式保存在本地,自身安全性较差;所以我们就通过cookie识别不同的用户,对应的在session里保存私密的信息以及超过4096字节的文本。
4、另外,上述所说的cookie和session其实是共通性的东西,不限于语言和框架
COOKIE
获取Cookie
request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
参数:
default: 默认值
salt: 加密盐
max_age: 后台控制过期时间
设置Cookie
rep = HttpResponse(...) rep = render(request, ...) rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='加密盐',...)
参数:
key, 键
value='', 值
max_age=None, 超时时间
expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)
path='/', Cookie生效的路径,/ 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问
domain=None, Cookie生效的域名
secure=False, https传输
httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
使用示例
def login(request):
if request.method == "POST":
user = request.POST.get("user")
pwd = request.POST.get("pwd")
# 校验用户名密码
if user == "alex" and pwd == "dashabi":
rep = redirect("/index/")
# rep.set_cookie("user", user) 明文的
# import datetime
# now = datetime.datetime.now()
# d = datetime.timedelta(seconds=10)
# rep.set_signed_cookie("user", user, salt="S8", expires=now+d) # 加盐处理,expires失效的具体时间
rep.set_signed_cookie("user", user, salt="S8", max_age=10) # 加盐处理,max_age有效期10秒
return rep
return render(request, "login.html")
def index(request):
# username = request.COOKIES.get("user") 取明文
username = request.get_signed_cookie("user", None, salt="S8") # 取加盐的
if not username:
# 表示没有登录
return redirect("/login/")
return render(request, "index.html", {"username": username})
Cookie版登陆校验,登录完成后仍然返回前一个页面
from django.shortcuts import render, redirect, HttpResponse from functools import wraps # Create your views here. # 检查用户是否登录的装饰器 def wrapper(func): @wraps(func) # 保持被装饰函数的函数名和注释内容用 def inner(request, *args, **kwargs): # 登录校验 cookie_k = request.get_signed_cookie("k", None, salt="xxxs8xxx") if cookie_k: ret = func(request, *args, **kwargs) else: next_url = request.get_full_path() ret = redirect("/login/?next={}".format(next_url)) return ret return inner def login(request): next_url = request.GET.get("next") if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") # 去数据库判断 if user == "alex" and pwd == "123456": if next_url: rep = redirect(next_url) else: rep = redirect("/index/") rep.set_signed_cookie("k", user, salt="xxxs8xxx", max_age=10) return rep return render(request, "login.html")
此时需要注意前端的form表单的active需要做相应的修改
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录</title> </head> <body> <form action="{{ request.get_full_path }}" method="post"> {% csrf_token %} <input type="text" name="user"> <input type="password" name="pwd"> <input type="submit" value="提交"> </form> </body> </html>
注销,删除cookie
def logout(request): # 退出功能 rep = redirect("/login/") rep.delete_cookie("k") # 删除cookie return rep
Session
Session的使用方法
def index(request): # 获取、设置、删除Session中数据 request.session['k1'] request.session.get('k1',None) request.session['k1'] = 123 request.session.setdefault('k1',123) # 存在则不设置 del request.session['k1'] # 所有 键、值、键值对 request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() # 用户session的随机字符串 request.session.session_key # 将所有Session失效日期小于当前日期的数据删除 request.session.clear_expired() # 检查 用户session的随机字符串 在数据库中是否 request.session.exists("session_key") # 删除当前用户的所有Session数据 request.session.delete()
request.session.flush() request.session.set_expiry(value) * 如果value是个整数,session会在些秒数后失效。 * 如果value是个datatime或timedelta,session就会在这个时间后失效。 * 如果value是0,用户关闭浏览器session就会失效。 * 如果value是None,session会依赖全局session失效策略。
Session版登陆验证
from functools import wraps def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.session.get("user"): return func(request, *args, **kwargs) else: return redirect("/login/?next={}".format(next_url)) return inner def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "alex" and pwd == "alex1234": # 设置session request.session["user"] = user # 获取跳到登陆页面之前的URL next_url = request.GET.get("next") # 如果有,就跳转回登陆之前的URL if next_url: return redirect(next_url) # 否则默认跳转到index页面 else: return redirect("/index/") return render(request, "login.html") @check_login def logout(request): # 删除所有当前请求相关的session request.session.delete() return redirect("/login/") @check_login def index(request): current_user = request.session.get("user", None) return render(request, "index.html", {"user": current_user})
Django中默认支持Session,其内部提供了5种类型的Session供开发者使用:
数据库(默认)
缓存
文件
缓存+数据库
加密cookie
数据库Session
Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。 a. 配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认) SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认) SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认) SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认) b. 使用 def index(request): # 获取、设置、删除Session中数据 request.session['k1'] request.session.get('k1',None) request.session['k1'] = 123 request.session.setdefault('k1',123) # 存在则不设置 del request.session['k1'] # 所有 键、值、键值对 request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() # 用户session的随机字符串 request.session.session_key # 将所有Session失效日期小于当前日期的数据删除 request.session.clear_expired() # 检查 用户session的随机字符串 在数据库中是否 request.session.exists("session_key") # 删除当前用户的所有Session数据 request.session.delete("session_key") ...
缓存Session
a. 配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎 SESSION_CACHE_ALIAS = 'default' # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置 SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串 SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径 SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名 SESSION_COOKIE_SECURE = False # 是否Https传输cookie SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输 SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存 b. 使用 同上
文件Session
a. 配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.file' # 引擎 SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() # 如:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串 SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径 SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名 SESSION_COOKIE_SECURE = False # 是否Https传输cookie SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输 SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存 b. 使用 同上
缓存+数据库
数据库用于做持久化,缓存用于提高效率 a. 配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # 引擎 b. 使用 同上
加密Cookie Session
a. 配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # 引擎 b. 使用 同上
公用设置项
SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认) SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认) SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
CBV中加装饰器相关
CBV实现的登录视图
class LoginView(View): def get(self, request): """ 处理GET请求 """ return render(request, 'login.html') def post(self, request): """ 处理POST请求 """ user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'alex' and pwd == "alex1234": next_url = request.GET.get("next") # 生成随机字符串 # 写浏览器cookie -> session_id: 随机字符串 # 写到服务端session: # { # "随机字符串": {'user':'alex'} # } request.session['user'] = user if next_url: return redirect(next_url) else: return redirect('/index/') return render(request, 'login.html')
要在CBV视图中使用我们上面的check_login装饰器,有以下三种方式:
from django.utils.decorators import method_decorator
1. 加在CBV视图的get或post方法上
from django.utils.decorators import method_decorator class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") @method_decorator(check_login) def post(self, request): print("Home View POST method...") return redirect("/index/")
2. 加在dispatch方法上
from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(check_login) def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
因为CBV中首先执行的就是dispatch方法,所以这么写相当于给get和post方法都加上了登录校验。
3. 直接加在视图类上,但method_decorator必须传 name 关键字参数
如果get方法和post方法都需要登录校验的话就写两个装饰器。
from django.utils.decorators import method_decorator @method_decorator(check_login, name="get") @method_decorator(check_login, name="post") class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
关于csrf_token的补充
CSRF Token相关装饰器在CBV只能加到dispatch方法上
备注:
csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件。
csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
from django.views.decorators.csrf import csrf_exempt, csrf_protect class HomeView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")