python【第二十一篇】Django模板继承、分页、cookie验证

时间:2024-03-31 16:07:20

1.模板继承

母版master.html

 {% block title %}{% endblock %}
2 {% block table-cont %}{% endblock %}

子板

{% extends 'master.html' %}
{% block title %}应用列表{% endblock %}
{% block table-cont %}
...
{% endblock %}

2.自定义分页

 #! /usr/bin/env python3
 # -*- coding:utf-8 -*-
 from django.utils.safestring import mark_safe

 class Page:
     def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
         self.current_page = current_page
         self.data_count = data_count
         self.per_page_count = per_page_count
         self.pager_num = pager_num

     @property
     def start(self):
         return (self.current_page - 1) * self.per_page_count

     @property
     def end(self):
         return self.current_page * self.per_page_count

     @property
     def total_count(self):
         v, y = divmod(self.data_count, self.per_page_count)
         if y:
             v += 1
         return v

     def page_str(self, base_url):
         page_list = []

         if self.total_count < self.pager_num:
             start_index = 1
             end_index = self.total_count + 1
         else:
             if self.current_page <= (self.pager_num + 1) / 2:
                 start_index = 1
                 end_index = self.pager_num + 1
             else:
                 start_index = self.current_page - (self.pager_num - 1) / 2
                 end_index = self.current_page + (self.pager_num + 1) / 2
                 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
                     end_index = self.total_count + 1
                     start_index = self.total_count - self.pager_num + 1

         if self.current_page == 1:
             prev = '<a class="page" href="javascript:void(0);">上一页</a>'
         else:
             prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
         page_list.append(prev)

         for i in range(int(start_index), int(end_index)):
             if i == self.current_page:
                 temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
             else:
                 temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
             page_list.append(temp)

         if self.current_page == self.total_count:
             nex = '<a class="page" href="javascript:void(0);">下一页</a>'
         else:
             nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
         page_list.append(nex)

         jump = """
         <input type='text'  /><a class="go" onclick='jumpTo(this, "%s?p=");'> 跳转</a>
     <script>
         function jumpTo(ths,base){
             var val = ths.previousSibling.value;
             location.href = base + val;
         }
     </script>
         """ % (base_url,)

         page_list.append(jump)

         page_str = mark_safe("".join(page_list))

         return page_str

view中:

 def host_list(request):
     if request.method == "GET":
         business_list = models.Business.objects.all()
         hosts_list = models.Host.objects.all()

         current_page = request.GET.get('p', 1)
         current_page = int(current_page)

         val = request.COOKIES.get('per_page_count', 10)
         val = int(val)
         page_obj = pagination.Page(current_page, len(hosts_list), val)
         data = hosts_list[page_obj.start:page_obj.end]
         page_str = page_obj.page_str("/cmdb/host/")

         return render(request, 'host-list.html', {'hosts_list': data,
                                                   'page_str': page_str,
                                                   'business_list': business_list})

3.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获取(不是绝对,底层抓包可以获取到也可以被覆盖)

js操作cookie

<script src='/static/js/jquery.cookie.js'></script>
$.cookie("list_pager_num", 30,{ path: '/' });