第八章(3)

  1. views:请求的其他信息
  2. 模板继承和引用
  3. 自定义函数(simple_tag & filter)
  4. 分页示例
  5. cookie
  6. CBV和FBV用户认证装饰器

1.views-请求的其他信息

1 from django.core.handlers.wsgi import  WSGIRequest
2 
3 request.environ
4 request.environ['HTTP_USER_AGENT']
View Code

2.模板继承和引用

1 urlpatterns = [
2     #path('admin/', admin.site.urls),
3     url(r'tp11',views.tp11),
4     url(r'tp12',views.tp11),
5     url(r'tp13',views.tp11),
6 
7 ]
urls.py
 1 def tp11(request):
 2 
 3     user_list = [1,2,3,]
 4 
 5     return render(request,'tp11.html',{'u':user_list})
 6 
 7 
 8 def tp12(request):
 9     name = 'root'
10 
11     return render(request, 'tp12.html', {'name': name})
12 
13 
14 def tp13(request):
15     status = '已删除'
16 
17     return render(request, 'tp13.html', {'status': status})
views.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>{% block title%} {% endblock %}</title>
 6     <link rel="stylesheet" href="/static/commcons.css" />
 7     <style>
 8         .pg-header{
 9             height: 50px;
10             background-color: seashell;
11             color: green;
12         }
13     </style>
14     {% block css %} {% endblock %}
15 <body>
16     <div class="pg-header">潇韩海</div>
17 
18     {% block content %} {% endblock %}
19     <div class="pg-header"></div>
20     <script src="/static/jquery-2.1.0.js"></script>
21     {% block js %} {% endblock %}
22 </body>
23 </html>
master.html
 1 {% extends 'master.html'%}
 2 
 3 {% block title %} 用户管理 {% endblock %}
 4 
 5 {% block content %}
 6     <ul>
 7         {% for i in u %}
 8             <li>{{ i }}</li>
 9         {% endfor %}
10     </ul>
11 
12     {% for i in u %}
13         {% include 'tag.html' %}
14     {% endfor %}
15 {% endblock %}
16 
17 {% block css %}
18     <style>
19         body{
20             background-color: red;
21         }
22     </style>
23 {% endblock %}
24 
25 {% block js %}
26     <script></script>
27 {% endblock %}
tp11.html
1 <form>
2     <input type="text"/>
3     <input type="submit" />
4 </form>
tag.html

3.自定义函数(simple_tag & filter)

simple_tag
a. app创建templatetags目录
b. 任意xxoo.py文件
c.创建template对象reqister
d.
   @register.simple_tag
   def func(a1,a2)
   	return "asasd"
   	
 e.settings中注册APP
 f. 顶部{% load xxoo %}
 g. {% 函数名 arg1 arg2%}
 
 缺点:
     参数任意
1  url(r'tp14/',views.tp14),
urls.py
 1 __author__ = 'Administrator'
 2 from django import template
 3 from django.utils.safestring import mark_safe
 4 
 5 register = template.Library()
 6 
 7 @register.simple_tag
 8 def houyafan(a1,a2,):
 9     return a1 + a2
10 
11 @register.filter
12 def jiajingze(a1,a2):
13     return a1 + str(a2)
app01/templatetags/xxoo.py
 1 {% load xxoo %}
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title></title>
 7 </head>
 8 <body>
 9     {{ name }}
10     {{ name|lower }}
11     {{ name|truncatechars:"3" }}
12 
13     {% houyafan  2  8  %}
14     
15     {{ "maliya"|jiajingze:"LS,YH" }}
16     
17      {% if "maliya"|jiajingze:"LS,YH" %}
18      {% endif %}
19 
20 
21 </body>
22 </html>
tp14.html

4.分页示例

1 url(r'user_list/',views. user_list),
urls.py
 1 LISI = []
 2 for i in range(109):
 3     LISI.append(i)
 4 
 5 def user_list(request):
 6     current_page = request.GET.get('p',1)
 7     current_page = int(current_page)
 8     start = (current_page-1) * 10
 9     end = current_page * 10
10     data = LISI[start:end]
11 
12     all_count = len(LISI)
13     count,y = divmod(all_count,10)
14     if y:
15         count += 1
16 
17     page_list = []
18     for i in range(1,count+1):
19         if i == current_page:
20             temp = '<a class="page active" href="/user_list/?p=%s">%s</a>' %(i,i)
21         else:
22             temp = '<a class="page" href="/user_list/?p=%s">%s</a>' %(i,i)
23 
24         page_list.append(temp)
25     page_str = mark_safe("".join(page_list))
26     return render(request,'user_list.html', {'li':data,'page_str':page_str})
views.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .pagination .page{
 8             display: inline-block;
 9             padding: 5px;
10             background-color: cyan;
11             margin: 5px;
12         }
13         .pagination .page.active{
14             background-color: brown;
15             color: white;
16         }
17     </style>
18 </head>
19 <body>
20     <ul>
21         {% for item in li %}
22             {% include 'li.html' %}
23         {% endfor %}
24     </ul>
25     <div class="pagination">
26         {{ page_str }}
27     </div>
28 </body>
29 </html>
user_list.html
1 <li>{{ item }}</li>
li.html

分页优化版

 1 from django.shortcuts import render
 2 from django.utils.safestring import mark_safe
 3 from  utils import pagination
 4 LISI = []
 5 for i in range(500):
 6     LISI.append(i)
 7 
 8 def user_list(request):
 9     current_page = request.GET.get('p',1)
10     current_page = int(current_page)
11 
12     val = request.COOKIES.get('per_page_count',10)
13     val = int(val)
14 
15     page_obj = pagination.Page(current_page,len(LISI),val)
16 
17     data = LISI[page_obj.start:page_obj.end]
18 
19     page_str = page_obj.page_str("/user_list")
20 
21     return render(request,'user_list.html', {'li':data,'page_str': page_str})
22     
23   ###############################################################################
24   from  utils import pagination
25 
26 LIST = []
27 for i in range(500):
28     LIST.append(i)
29 
30 def user_list(request):
31     current_page = request.GET.get('p', 1)
32     current_page = int(current_page)
33 
34     val = request.COOKIES.get('per_page_count')
35     val = int(val)
36     page_obj = pagination.Page(current_page,len(LIST),val)
37     data = LIST[page_obj.start:page_obj.end]
38 
39     page_str = page_obj.page_str("/user_list/")
40 
41     return render(request,'user_list.html', {'li': data,'page_str': page_str})
views.py
 1 __author__ = 'wei.han'
 2 from django.utils.safestring import mark_safe
 3 
 4 
 5 class Page:
 6     def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
 7         #用户点击值
 8         self.current_page = current_page
 9         #数据总数
10         self.data_count = data_count
11         #每页显示10条数据
12         self.per_page_count = per_page_count
13         #7页
14         self.pager_num = pager_num
15 
16     #开始(显示居中)
17     @property
18     def start(self):
19         return (self.current_page - 1) * self.per_page_count
20 
21     # 结束(显示居中)
22     @property
23     def end(self):
24         return self.current_page * self.per_page_count
25 
26     #总页数
27     @property
28     def total_count(self):
29         v, y = divmod(self.data_count, self.per_page_count)
30         if y:
31             v += 1
32         return v
33 
34     #url
35     def page_str(self, base_url):
36         page_list = []
37 
38         if self.total_count < self.pager_num:
39             start_index = 1
40             end_index = self.total_count + 1
41         else:
42             if self.current_page <= (self.pager_num + 1) / 2:
43                 start_index = 1
44                 end_index = self.pager_num + 1
45             else:
46                 start_index = self.current_page - (self.pager_num - 1) / 2
47                 end_index = self.current_page + (self.pager_num + 1) / 2
48                 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
49                     end_index = self.total_count + 1
50                     start_index = self.total_count - self.pager_num + 1
51 
52         if self.current_page == 1:
53             prev = '<a class="page" href="javascript:void(0);">上一页</a>'
54         else:
55             prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
56         page_list.append(prev)
57 
58         for i in range(int(start_index), int(end_index)):
59             if i == self.current_page:
60                 temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
61             else:
62                 temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
63             page_list.append(temp)
64 
65         if self.current_page == self.total_count:
66             nex = '<a class="page" href="javascript:void(0);">下一页</a>'
67         else:
68             nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
69         page_list.append(nex)
70 
71         jump = """
72         <input type='text'  /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
73         <script>
74             function jumpTo(ths,base){
75                 var val = ths.previousSibling.value;
76                 location.href = base + val;
77             }
78         </script>
79         """ % (base_url,)
80 
81         page_list.append(jump)
82 
83         page_str = mark_safe("".join(page_list))
84 
85         return page_str
pagination.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         .pagination .page{
 8             display: inline-block;
 9             padding: 5px;
10             background-color: cyan;
11             margin: 5px;
12         }
13         .pagination .page.active{
14             background-color: brown;
15             color: white;
16         }
17     </style>
18 </head>
19 <body>
20     <ul>
21         {% for item in li %}
22             {% include 'li.html' %}
23         {% endfor %}
24     </ul>
25 
26     <div>
27         <select id="ps" onchange="changePageSize(this)">
28             <option value="10">10</option>
29             <option value="15">30</option>
30             <option value="20">40</option>
31             <option value="30">50</option>
32         </select>
33     </div>
34 
35     <div class="pagination">
36         {{ page_str }}
37     </div>
38 
39     <script src="/static/jquery-1.12.4.js" type="text/javascript"></script>
40     <script  src="/static/jQuery-cookie.js"  type="text/javascript"></script>
41     <script>
42 
43         $(function() {
44             var v = $.cookie('per_page_count', {'path': "/user_list/`"});
45             $('#ps').val(v);
46         });
47 
48         function changePageSize(ss){
49             var v = $(ss).val();
50             console.log(v);
51             $.cookie('per_page_count',v,{'path': "/user_list/"});
52 
53             location.reload();
54         }
55     </script>
56 </body>
57 </html>
user_list.html

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

设置cookie有限时间

request.COOKIES.get('username111')

reqpone = render(request,'index.html')

设置cookie,关闭浏览器后就失效
response.set_cookie('key','value')

设置cookie,10秒后失效
response.set_cookie('username111','value',max_age=10)
return response

设置cookie,5秒后失效
import datetime
current_date = datetime.datetime.utcnow()
current_date = current_date + datetime.timedelta(seconds=5)
res.set_cookie('username111',u,expires=current_date)

 cookie加密

#request.COOKIES.get('...')
#request.set_cookie(...)
obj = HttpResponse('s')
加密
obj.set_signed_cookie('username','kanbazi',salt='jiamizifuchuan')
获取加密
request.get_signed_cookie('username',salt="jiamizifuchuan")

return response

6.CBV和FBV用户认证装饰器

FBV

1 url(r'index/',views.index),
urls.py
 1 from django.shortcuts import render,redirect
 2 from django.utils.safestring import mark_safe
 3 
 4 user_info = {
 5     'dachengzi': {'pwd': "123"},
 6     'kanbazi': {'pwd': "123"},
 7 }
 8 
 9 
10 def login(request):
11     if request.method == "GET":
12         return render(request, 'login.html')
13     if request.method == "POST":
14         u = request.POST.get('username')
15         p = request.POST.get('pwd')
16         dic = user_info.get(u)
17         if not dic:
18             return render(request,'login.html')
19         if dic['pwd'] == p:
20             res = redirect('/index/')
21             res.set_cookie('username111',u)
22             return res
23         else:
24             return render(request,'login.html')
25             
26             
27 def auth(func):
28     def inner(request,*arges,**kwargs):
29         v = request.COOKIES.get('username111')
30         if not v:
31             return redirect('/login/')
32         return func(request,*arges,**kwargs)
33     return inner
34     
35 
36 @auth
37 def index(request):
38     v = request.COOKIES.get('username111')
39     return render(request,'index.html',{'current_user': v})
views.py

CBV

 1 from django import views
 2 from django.utils.decorators import method_decorator
 3 
 4 @method_decorator(auth,name='dispatch')
 5 class Order(views.View):
 6 
 7     # @method_decorator(auth)
 8     # def dispatch(self,request, *args,**kwargs):
 9     #      return super(Order,self).dispatch(request, *args, **kwargs)
10 
11     # @method_decorator(auth)
12     def get(self,request):
13         v = request.COOKIES.get('username111')
14         return render(request,'index.html',{'current_user': v})
15 
16     def post(self,request):
17         v = request.COOKIES.get('username111')
18         return render(request,'index.html',{'current_user': v})
CBV
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <form action="/login/" method="POST">
 9         <input type="text" name="username" placeholder="用户名"/>
10         <input type="password" name="pwd" placeholder="密码"/>
11         <input type="submit"/>
12     </form>
13 </body>
14 </html>
login.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <h1>欢迎登录:{{ current_user }}</h1>
 9 </body>
10 </html>
index.html
posted @ 2018-05-26 16:42  ༺༽秋水.无痕༼༻  阅读(117)  评论(0编辑  收藏  举报
……