博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第八章(3)
阅读量:5106 次
发布时间:2019-06-13

本文共 10834 字,大约阅读时间需要 36 分钟。

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

1.views-请求的其他信息

1 from django.core.handlers.wsgi import  WSGIRequest2 3 request.environ4 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  2  3  4     
5 {% block title%} {% endblock %} 6
7 14 {% block css %} {% endblock %}15 16
潇韩海
17 18 {% block content %} {% endblock %}19
20 21 {% block js %} {% endblock %}22 23
master.html
1 {% extends 'master.html'%} 2  3 {% block title %} 用户管理 {% endblock %} 4  5 {% block content %} 6     
    7 {% for i in u %} 8
  • {
    { i }}
  • 9 {% endfor %}10
11 12 {% for i in u %}13 {% include 'tag.html' %}14 {% endfor %}15 {% endblock %}16 17 {% block css %}18 23 {% endblock %}24 25 {% block js %}26 27 {% endblock %}
tp11.html
1 
2
3
4
tag.html

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

simple_taga. app创建templatetags目录b. 任意xxoo.py文件c.创建template对象reqisterd.   @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 + a210 11 @register.filter12 def jiajingze(a1,a2):13     return a1 + str(a2)
app01/templatetags/xxoo.py
1 {% load xxoo %} 2  3  4  5     
6 7 8 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 22
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 * 1010     data = LISI[start:end]11 12     all_count = len(LISI)13     count,y = divmod(all_count,10)14     if y:15         count += 116 17     page_list = []18     for i in range(1,count+1):19         if i == current_page:20             temp = '%s' %(i,i)21         else:22             temp = '%s' %(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  2  3  4     
5 Title 6 18 19 20
    21 {% for item in li %}22 {% include 'li.html' %}23 {% endfor %}24
25
28 29
user_list.html
1 
  • {
    { item }}
  • 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 pagination25 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_count11         #每页显示10条数据12         self.per_page_count = per_page_count13         #7页14         self.pager_num = pager_num15 16     #开始(显示居中)17     @property18     def start(self):19         return (self.current_page - 1) * self.per_page_count20 21     # 结束(显示居中)22     @property23     def end(self):24         return self.current_page * self.per_page_count25 26     #总页数27     @property28     def total_count(self):29         v, y = divmod(self.data_count, self.per_page_count)30         if y:31             v += 132         return v33 34     #url35     def page_str(self, base_url):36         page_list = []37 38         if self.total_count < self.pager_num:39             start_index = 140             end_index = self.total_count + 141         else:42             if self.current_page <= (self.pager_num + 1) / 2:43                 start_index = 144                 end_index = self.pager_num + 145             else:46                 start_index = self.current_page - (self.pager_num - 1) / 247                 end_index = self.current_page + (self.pager_num + 1) / 248                 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:49                     end_index = self.total_count + 150                     start_index = self.total_count - self.pager_num + 151 52         if self.current_page == 1:53             prev = '上一页'54         else:55             prev = '上一页' % (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 = '%s' % (base_url, i, i)61             else:62                 temp = '%s' % (base_url, i, i)63             page_list.append(temp)64 65         if self.current_page == self.total_count:66             nex = '下一页'67         else:68             nex = '下一页' % (base_url, self.current_page + 1,)69         page_list.append(nex)70 71         jump = """72         GO73         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  2  3  4     
    5 6 18 19 20
      21 {% for item in li %}22 {% include 'li.html' %}23 {% endfor %}24
    25 26
    27
    33
    34 35
    38 39 40 41 56 57
    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 datetimecurrent_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 res23 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 inner34 35 36 @auth37 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  2  3  4     
    5 Title 6 7 8
    9
    10
    11
    12
    13 14
    login.html
    1  2  3  4     
    5 Title 6 7 8

    欢迎登录:{
    { current_user }}

    9 10
    index.html

    转载于:https://www.cnblogs.com/hanwei999/p/9093527.html

    你可能感兴趣的文章
    windows service承载的web api宿主搭建(Microsoft.Owin+service)
    查看>>
    PAT 1009. 说反话 (20)
    查看>>
    动态改变EnterpriseLibary数据库访问链接字符串的三种方法
    查看>>
    子模块的设计与分析
    查看>>
    (Mark) (Ubuntu)Ubuntu 12.04 LTS 通过ppa安装Fcitx 搜狗输入法 (Linux) (输入法)
    查看>>
    html5+canvas
    查看>>
    3月30日
    查看>>
    [转] Android root 原理
    查看>>
    知识点集锦
    查看>>
    Remove Duplicates from Sorted List I&&II
    查看>>
    毒瘤题No.007-byFHS
    查看>>
    javaweb学习总结(十一)——使用Cookie进行会话管理
    查看>>
    网络编程
    查看>>
    Struts2类型转换器
    查看>>
    windows下composer 使用
    查看>>
    java的异常处理机制
    查看>>
    NFS根文件系统
    查看>>
    Javascript精华实例代码
    查看>>
    Java内存区域与内存溢出异常---对象的内存布局和对象的访问定位
    查看>>
    【转载】Android 的 Handler 机制实现原理分析
    查看>>