zoukankan      html  css  js  c++  java
  • Django学习之

    视图:Views

    获取用户请求的方法:
    1: request.GET
    2: request.POST
    3: request.FILES
    # checkbox 等多选文件
    4:request.POST.getlist()
    # 上传文件,form标签要做特殊设置
      obj = request.FILES.get('fafafa')
      obj.name 上传的文件名
      obj.chunks() 上传的文件内容
      f = open(obj.name,mode='wb')
      for item in obj.chunks():
        f.write(item)
      f.close()
    实例:注册register视图函数

     1 def register(request):
     2     if request.method == 'GET':
     3         return render(request,'register.html')
     4     elif request.method == 'POST':
     5         uname = request.POST.get('username',None)
     6         upwd = request.POST.get('pwd',None)
     7         print('用户名:',uname,'密码:',upwd)
     8         ugender = request.POST.get('gender',None)
     9         print('性别:', ugender)
    10         ufavor = request.POST.getlist('favor',None)
    11         print('爱好:',ufavor)
    12         ucity = request.POST.getlist('city',None)
    13         print('城市:',ucity)
    14         obj = request.FILES.get('upfile')
    15         tmppath = os.path.join('upload',obj.name)
    16         f = open(tmppath,mode='wb')
    17         for item in obj.chunks():
    18             f.write(item)
    19         return HttpResponse('注册完毕')
    20     else:
    21         return redirect('/register')
    View Code

    5:request.method
    6:request.path_info
    7:request.COOKIES
    request.body # 所有提交的数据的原生值
      - request.POST
      - request.GET
      - request.FILES
      - request.xxx.getlist
    request.Meta # 获取提交的数据的请求头信息,如客户端游览器这里可以提取到
      - request.method(POST,GET,PUT)
      - request.path_info
      - request.COOKIES
    返回3种:
      return HttpResponse('字符串或者字节')
      return render()
      return redirect()
    返回cookie,并且可以自定义添加响应头返回给客户端,客户端游览器可以在响应头查看到返回的值
      response = HttpResponse('china')
      response['name'] = jack
      response.set_cookie()
      return response


    FBV & CBV
    FBV ( function base view) :就是在视图里使用函数处理请求。
    /index ==> 函数
    CBV ( class base view) :就是在视图里使用类处理请求
    /index ==> 类
    实例cbv写法:

     1 urls写法:
     2 url(r'^cbv',views.cbv.as_view()),
     3 
     4 视图函数:
     5 class cbv(View):
     6     def dispath(self,request,*args,**kwargs):
     7         # 调用父类中的dispath
     8         print('before')
     9         result = super(cbv,self).dispatch(request,*args,**kwargs)
    10         print('after')
    11         return result
    12     def get(self,request):
    13         print(request.method)
    14         return render(request,'CBV.html')
    15     def post(self,request):
    16         print(request.method,'POST')
    17         return render(request,'CBV.html')
    CBV

    建议:俩者都用
    CBV / FBV 装饰器
    FBV 装饰器:
      def auth(func):
        def inner(request,*args,**kwargs):
          v = request.COOKIES.get('uname')
          if not v:
            return redirect('/ug/login')
          return func(*args,**kwargs)
        return inner
    CBV 装饰器:
      from django import views
      from django.utils.decorators import method_decorator
      class Order(views.View):
        @method_decorator(auth)
        def get(self,request):
          v = request.COOKIES.get('uname')
          return render(request,'index.html',{'current_user':v})
        def post(self,request):
          v = request.COOKIES.get('uname')
          return render(request,'index.html',{'current_user':v})

    - 获取请求的其他信息
    通过pring(type(request))获取模块文件名
    from django.core.handlers.wsgi import WSGIRequest
    request.environ # 输出请求的所有信息
    request.environ['HTTP_USER_AGENT'] # 获取http_user_agent数据
    通过以上方法提取环境数据
    - 分页(自定义)
    XSS:
    前台:{{ page_str|safe }}
    后台:mark_safe(page_str)
    分页实例:

    html页面

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>分页</title>
     6     <style>
     7         .page {
     8             background:#9acfea;
     9             padding: 5px;
    10             margin:5px;
    11         }
    12         .active{
    13             background:red;
    14         }
    15     </style>
    16 </head>
    17 <body>
    18     <ul>
    19         {% for i in li %}
    20         {% include 'li.html' %}
    21         {% endfor %}
    22     </ul>
    23 {#    {{ page_str|safe }}#}
    24     <div style="float: left;">
    25         <select id='ps' onchange="changePageSize(this);">
    26             <option value="10">10</option>
    27             <option value="50">50</option>
    28             <option value="100">100</option>
    29         </select>
    30     </div>
    31     <div style="float: left;">
    32         {{ page_str }}
    33     </div>
    34 <script src="/static/jquery-1.12.4.min.js"></script>
    35 <script src="/static/jquery-cookie/jquery.cookie.js"></script>
    36 <script>
    37     /*select选项框修改为当前显示数量*/
    38     $(function () {
    39         var v = $.cookie('per_page_count',{'path':"/ug/userlist"});
    40         $('#ps').val(v)
    41     });
    42     /*select选项框选择后自动刷新页面*/
    43     function changePageSize(ths) {
    44         var v = $(ths).val();
    45         $.cookie('per_page_count',v,{'path':"/ug/userlist"});
    46         location.reload();
    47     }
    48 </script>
    49 </body>
    50 </html>
    View Code

    视图函数

     1 from utils import pagination
     2 ulist = []
     3 for i in range(1009):
     4     ulist.append(i)
     5 def userlist(request):
     6     current_page = request.GET.get('p',1)
     7     current_page = int(current_page)
     8     val = request.COOKIES.get('per_page_count',10)
     9     page_obj = pagination.Page(current_page,len(ulist),int(val))
    10     data = ulist[page_obj.start:page_obj.end]
    11     page_str = page_obj.page_str('/ug/userlist/')
    12     return render(request,'userlist.html',{'li':data,'page_str':page_str})
    View Code

    后台模块:pagination

     1 #!/bin/env python
     2 #Author: zhaoyong
     3 from django.utils.safestring import mark_safe
     4 class Page:
     5     '''
     6     实现分页显示功能类
     7     '''
     8     def __init__(self,current_page,data_count,per_page_count = 10,pager_num=7):
     9         '''
    10         用于分页模块
    11         :param current_page: 当前页
    12         :param data_count: 数据总个数
    13         ;:param per_page_count: 每页显示数据数量
    14         ;:param pager_num: 每页的页码总数
    15         '''
    16         self.current_page = current_page
    17         self.data_count = data_count
    18         self.per_page_count = per_page_count
    19         self.pager_num = pager_num
    20     @property
    21     def start(self):
    22         ''' 列表切片起始索引位置'''
    23         return (self.current_page - 1) * self.per_page_count
    24     @property
    25     def end(self):
    26         ''' 列表切片结束索引位置'''
    27         return self.current_page * self.per_page_count
    28     @property
    29     def all_count(self):
    30         '''生成页码的总数'''
    31         v, y = divmod(self.data_count, self.per_page_count)
    32         if y:
    33             v += 1
    34         return v
    35     def page_str(self,base_url):
    36         ''' 实现具体的分页显示'''
    37         page_list = []
    38         if self.all_count < self.pager_num:
    39             start_page = 1
    40             end_page = self.all_count + 1
    41         else:
    42             if self.current_page < (self.pager_num + 1) / 2:
    43                 start_page = 1
    44                 end_page = self.pager_num + 1
    45             else:
    46                 start_page = self.current_page - (self.pager_num - 1) / 2
    47                 end_page = self.current_page + (self.pager_num + 1) / 2
    48                 if self.current_page + (self.pager_num - 1) / 2 > self.all_count:
    49                     start_page = self.all_count - self.pager_num + 1
    50                     end_page = self.all_count + 1
    51 
    52         if self.current_page <= 1:
    53             prv = '<a class="page" href="javascript:void(0);">上一页</a>'
    54         else:
    55             prv = '<a class="page" href=%s?p=%s>上一页</a>' % (base_url,self.current_page - 1)
    56         page_list.append(prv)
    57         for i in range(int(start_page), int(end_page)):
    58             if i == self.current_page:
    59                 temp = '<a class="page active" href=%s?p=%s>%s</a>' % (base_url,i, i)
    60             else:
    61                 temp = '<a class="page" href=%s?p=%s>%s</a>' % (base_url,i, i)
    62             page_list.append(temp)
    63         if self.current_page == self.all_count:
    64             next = '<a class="page" href="javascript:void(0);">下一页</a>'
    65         else:
    66             next = '<a class="page" href=%s?p=%s>下一页</a>' % (base_url,self.current_page + 1)
    67         page_list.append(next)
    68         jump = '''
    69             <input type='text' /><a onclick="jumpto(this,'%s?p=');">GO</a>
    70             <script>
    71                 function jumpto(ths,base){
    72                     var val = ths.previousSibling.value;
    73                     if(val.length != 0){
    74                     location.href = base + val;
    75                     }
    76                 }
    77             </script>
    78         ''' % (base_url)
    79         page_list.append(jump)
    80         page_str = mark_safe(''.join(page_list))
    81         return page_str
    View Code
  • 相关阅读:
    .net中数据库事务机制
    位图排序
    JavaScript实现手动画线
    CSS 样式
    我的知识计划
    开发民政信息采集工具有感
    系统小技巧
    C++的学习笔记
    Android核心服务学习笔记
    突然想到的“社会发展历程”
  • 原文地址:https://www.cnblogs.com/zy6103/p/7551461.html
Copyright © 2011-2022 走看看