Cookie、Session和自定义分页与django内置分页
为什么使用Cookie:因为HTTP请求是没有状态的,每一次请求都是独立的。
什么是Cookie:Cookie就是保存在浏览器上的键值对,服务端控制着响应,在响应里添加一个键值对,让浏览器在本地保存,下一次请求的时候,自动携带这个键值对,是在浏览器端设置的,浏览器端也可以禁用Cookie。
Cookie的设置,以及使用装饰器验证浏览器的登录状态
from django.shortcuts import render,HttpResponse,redirect # Create your views here. def login(request): if request.method == "POST": name = request.POST.get("name") pwd = request.POST.get("pwd") if name == 'alex' and pwd == '123123': next = request.GET.get('next') print(next) if next: res = redirect(next) res.set_signed_cookie("is_login","1",salt="s10nb",max_age=10) return res res = redirect('/app01/home/') res.set_signed_cookie("is_login","1",salt="s10nb" ,max_age=10) return res return render(request, 'app01/login.html') def home(request): res = request.get_signed_cookie("is_login",default="0",salt="s10nb") if res == '1': return render(request, 'app01/home.html') else : return redirect('/app01/login/') def timmer(func): def wrapper(request): res = request.get_signed_cookie("is_login",default="0",salt="s10nb") if res == '1': ret = func(request) return ret else : next_url = request.path_info print(next_url) return redirect('/app01/login/?next={}'.format(next_url)) return wrapper @timmer def index(request): return render(request, 'app01/index.html')
默认关闭浏览器,Cookie值就失效,可以设置时长max_age=7*24*60*60(七天失效)
注销登录
def logout(request): rep = redict("/app01/login/") rep.delete_cookie('is_login') return rep
Session
Session是保存在浏览器上的键值对,必须依赖Session,服务端生成的Cookie返回到浏览器,跟Cookie匹配的Session保存在服务器端,下次再登录时,根据Cookie获取Seeion值,存储的数据多,较为安全。
设置Session
request.session['is_login']='1'
获取Session值
首先获取Cookie的随机字符串,根据字符串的值去数据库取Seeion的数据,解密,把Session值反序列化成字典,然后在字典里可以根据key取值。
from django.shortcuts import render,HttpResponse,redirect # Create your views here. def login(request): if request.method == "POST": name = request.POST.get("name") pwd = request.POST.get("pwd") if name == 'alex' and pwd == '123123': next = request.GET.get('next') print(next) if next: res = redirect(next) request.session['is_login']='1' return res res = redirect('/app02/home/') request.session['is_login']='1' return res return render(request, 'app02/login.html') def home(request): res = request.session.get('is_login') if res == '1': return render(request, 'app02/home.html') else : return redirect('/app02/login/') def timmer(func): def wrapper(request): res = request.session.get('is_login') if res == '1': ret = func(request) return ret else : next_url = request.path_info print(next_url) return redirect('/app02/login/?next={}'.format(next_url)) return wrapper @timmer def index(request): return render(request, 'app02/index.html')
注销登录,删除Session和Cookie数据
def logout(request): request.session.flush() # request.session.delete()只删除session不删除cookie return redirect("/app02/login")
request.session.set_expiry(value)
value如果是整数,就是多少秒之后失效
value如果是datatime或者timemelta,session就会在这个时间后失效
value如果是0,关闭浏览器就失效。
SESSION_COOKIE_AGE=129600 session的Cookie失效日期默认为2周。
SESSION_SAVE_EVERY_REQUEST = True 设置后,每一次的请求都重新保存session
默认session修改后才重新保存
自定义分页
首选数据库批量创建数据
import os,sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ajax_demo.settings") import django django.setup() from app01 import models objs = [models.Userinfo(name="第{}个".format(i)) for i in range(105)] models.Userinfo.objects.bulk_create(objs,10)
views.py
#分页 def page_s(request): objs = models.Userinfo.objects.all() page_line = len(objs) m,n = divmod(page_line,10) page_sum = m if n>0: page_sum = m+1 # page_sum=[i for i in range(1,page_sum+1)] Page_sum = page_sum+1 page_id = request.GET.get('page_id') page_start = 0 page_end = 10 pro_page_id = 0 net_page_id = 2 page_sum_start = 1 page_sum_end = 11 if page_sum<11: page_sum_end=page_sum if page_id : page_id = int(page_id) page_start = (page_id-1)*10 page_end = (page_id)*10 pro_page_id = page_id-1 net_page_id = page_id+1 if page_id - 5 >0 and page_id +5 <=page_sum: page_sum_start = page_id -5 page_sum_end = page_id +5 if page_id +5 >page_sum: page_sum_start = page_sum-10 page_sum_end = page_sum page_sum =[i for i in range(page_sum_start,page_sum_end+1)] print(page_start,page_end) objs = objs[page_start:page_end] print(objs) return render(request,'page_s.html', {"objs":objs, "page_sum":page_sum, "pro_page_id":pro_page_id, "net_page_id":net_page_id, "Page_sum":Page_sum})
page_s.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> </head> <body> <table> <thead> <tr> <td></td> </tr> </thead> <tbody> {% for obj in objs %} <tr> <td> {{ obj.name }} </td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation" class="pull-right"> <ul class="pagination"> <li> <a href="/page_s/?page_id={{ pro_page_id }}" class="btn {% if pro_page_id == 0 %} disabled {% endif %} " aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% for page_sigle in page_sum %} <li><a href="/page_s/?page_id={{ page_sigle }}">{{ page_sigle }}</a></li> {% endfor %} <li> <a href="/page_s/?page_id={{ net_page_id }}" class="btn {% if net_page_id == Page_sum %} disabled {% endif %} aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> <script src="/static/jquery-3.3.1.min.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> </body> </html>
简单分页
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <ul> {% for item in posts %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if posts.has_previous %} <a href="?p={{ posts.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ posts.number }} of {{ posts.paginator.num_pages }}. </span> {% if posts.has_next %} <a href="?p={{ posts.next_page_number }}">Next</a> {% endif %} </span> </div> </body> </html> Html
内置分页扩展
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class CustomPaginator(Paginator): def __init__(self, current_page, max_pager_num, *args, **kwargs): """ :param current_page: 当前页 :param max_pager_num:最多显示的页码个数 :param args: :param kwargs: :return: """ self.current_page = int(current_page) self.max_pager_num = max_pager_num super(CustomPaginator, self).__init__(*args, **kwargs) def page_num_range(self): # 当前页面 # self.current_page # 总页数 # self.num_pages # 最多显示的页码个数 # self.max_pager_num print(1) if self.num_pages < self.max_pager_num: return range(1, self.num_pages + 1) print(2) part = int(self.max_pager_num / 2) if self.current_page - part < 1: return range(1, self.max_pager_num + 1) print(3) if self.current_page + part > self.num_pages: return range(self.num_pages + 1 - self.max_pager_num, self.num_pages + 1) print(4) return range(self.current_page - part, self.current_page + part + 1) L = [] for i in range(999): L.append(i) def index(request): current_page = request.GET.get('p') if not current_page: current_page=1 paginator = CustomPaginator(current_page, 11, L, 10) # per_page: 每页显示条目数量 # count: 数据总个数 # num_pages:总页数 # page_range:总页数的索引范围,如: (1,10),(1,200) # page: page对象 try: posts = paginator.page(current_page) print('post::::',posts,type(posts)) # has_next 是否有下一页 # next_page_number 下一页页码 # has_previous 是否有上一页 # previous_page_number 上一页页码 # object_list 分页之后的数据列表 # number 当前页 # paginator paginator对象 except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: print('*'*120) posts = paginator.page(paginator.num_pages) return render(request, 'index.html', {'posts': posts})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> </head> <body> <div class="container"> <ul> {% for item in posts %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> <nav aria-label="Page navigation"> <ul class="pagination"> {% if posts.has_previous %} <li> <a href="?p={{ posts.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% endif %} {% for i in posts.paginator.page_num_range %} <li><a href="?p={{ i }}">{{ i }}</a></li> {% endfor %} {% if posts.has_next %} <li> <a href="?p={{ posts.next_page_number }}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> {% endif %} </ul> </nav> {#<span class="current">#} {#Page {{ posts.number }} of {{ posts.paginator.num_pages }}.#} {#</span>#} </div> </div> <script src="/static/jquery-3.3.1.js"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> </body> </html>
I can feel you forgetting me。。 有一种默契叫做我不理你,你就不理我