zoukankan      html  css  js  c++  java
  • Python学习笔记第二十一周

    目录:  

      

       1、URL

       2、Models

        - 操作

       3、Templates

        - html模板的使用

        - 自定义函数

       4、cookie和session

       5、分页(自定义分页)

       6、Form验证

    内容:

      1、URL

       

        默认值:

    urls.py
    
    url(r'^index/', views.index, {'name': 'root'}),
    
    views.py
    def index(request,name):
        print(name)
        return HttpResponse('ok')
    View Code

         命名空间:

             namespace是添加在name前面,和name结合一起生成URL的方法

    #urls.py中
    from django.conf.urls import url,include
    
    urlpatterns = [
        url(r'^a/',include('app01.urls',namespace='author')),
    ]
    
    #app01的urls.py中
    from django.conf.urls import url
    from app01 import views
    app_name = 'app01'
    urlpatterns = [
        url(r'^index/',views.index, name='index'),
    ]
    #app01的views中
    def index(request):
        v = reverse('author:index')
        print(v)
        return HttpResponse('ok')
    View Code

           备注:

          模板语言中需要{% url   'author:index' %}

         

          请求周期:

          url -> 路由->函数或者类-> 返回字符串或者模板语言

          Form表单提交:

            提交-> url->函数或者类中的方法处理,处理完毕后返回给用户:

              HttpReponse()或者render()或者redirect()无论哪种方法,最后提交给用户的都是已经处理过的页面

              用户看到的永远都是已经处理完成的界面,当接受到redirect时自动发起一个新的URL

        

          Ajax:

            $.ajax({

              url:'/index/',

              data:{'k':'v'},

              dataType: 'JSON',

              type: 'POST',

              traditional: true,

              success: function(data){

                 location.reload()     #刷新

                 locatin.href='某个地址' #跳转             

              }        

            })

            提交 -> url  -> 函数或者类中的方法

                  HttpResponse()

                  render(request, 'index.html',{'k':'v'})

            生成字符串返回给用户

       2、Views

        请求的其他信息

        

        

       3、Models

        - 操作

       3、Templates

        - html模板的使用

        a) 在模板中定义:

        {% block content %} {%  endblock %}

        b) 在其他html中:

        最上面定义:

        {% extends   ‘模板页名称’%}

        

        {% block content %}

        自定义内容

        {%  endblock %}

        备注:

        由于css和js每个网页有可能会修改,所以需要修改:

        1、在</style>下面写{% block css %}{% endblock%}

        2、在</script>下面写{% block js%}{% endblock%}

        这样在子版调用可以分别设置

        母版html类型:

        1、extends:  每个模板的继承,只能继承一个模板

        2、include:   {% include ‘tag-name’%}  #可以定义多个并可重复调用

        - 自定义函数(自定义simple tag) 自定义函数也是在模板里使用的方法

        simple_tag:

        a、在某个app里创建一个templatetags目录,名字不能改

        b、在这个目录下创建一个任意py文件

        c、在这个文件中导入:

    from django import template
    from django.utils.safestring import mark_safe
    
    register = template.Library()
    @register.simple_tag

           d、创建函数: 

    def func(a1,a2,a3...):
        return 'abc'

           e、settings文件中注册APP

         f、html文件中顶部{% load  '该py文件' %}

          g、html引用{%  函数名   arg1   arg2  arg*  %}#使用时必须使用该方式调用

        filter:

        filter与simpe_tag比较:

        1、filter与simple_tag定义类似,所以a-b步骤一样,c步骤中@register.simple_tag需要改成@register.filter

         2、在html中调用,filter最多只能调用两个参数,同时方法为{{ ‘参数1’|函数名:'参数二' }}中间连空格都没法添加,或者{{ ‘参数1’|函数名:数字 }}形式

         3、filter可以在{%if  ‘参数1’|函数名:'参数二' %}{% endif%} filter可以作为if条件来操作

       4、cookie和session

        1、cookie:

          cookie是保存在用户浏览器的一个键值对,用来记录用户登录信息

        def login(request):

          当用户名密码核对成功后:

            res = redirect('/index/')#将跳转到index界面

            res.set_cookie('name': username) #设置cookie值

        def index(request):

          cookie = request.COOKIES.get('name') #获取cookie

          if not cookie:

            return redict(‘/login/’)#如何cookie没有获取到就要跳转会login界面

          return render(request,'index.html',{'current_name':  cookie}) #这样可以显示谁登录了

          

          cookie能提供的功能:

            从请求中获取cookie:cookie是已字典的形式存在

              1、request.COOKIE[‘username’]

              2、request.COOKE.get(‘username’) 

            生成cookie:

             1、设置cookie,关闭浏览器就失效

              response.set_cookie(‘key’,'value')

             return response

            2、cookie参数:        

    key,               键
    value=‘’,          值
    max_age=None,      超时时间
    expires=None        超时时间(IE requires expires, so set it if hasnt;t been already)
    path='/',           cookie生效的路径,/表示根路径,特殊的:根路径cookie可以被任何url页面访问,如果写成别的路径,比如/index表示只能在index的url中使用
    domain=None,       cookie生效域名
    secure=False        https传输
    httponly=False      只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)

            由于cookie保存再客户端的电脑上,所以JavaScript和jquery也可以操作cookie

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

            例子:

              1、response.set_cookie(‘key’,'value',max_age=10)#设置cookie在10s后失效

              2、import datetime      

                current_date = datetime.datetime.utcnow()

                current_date += datetime.timedelta(seconds=10)

                response.set_cookie(‘key’,'value',expires=current_date)                  

              3、response.set_cookie(‘user_type’,'abcabd',httponly=True)#设置后没法通过js抓取到该cookie

                4、juery-cookie:

                下载jquery-cookie.js文件:由于它是jquery的插件,用的时候必须放在jquery下面

                网址:plugins.jquery.com/cookie

                $.cookie('k1','v1') 设置值

                $.cookie('k1')       获取值

                $.cookie('k','v',{'path':})

              通过cookie完成页面显示条目数功能:

              

    <body>
        <ul>
            {% for item in li %}
             <li>{{ item }}</li>
            {% endfor %}
            {{ page_str }}
        </ul>
        <div>
            <select id="ps" onchange="changePageSize(this)">
                <option value="10">10</option>
                <option value="30">30</option>
                <option value="50">50</option>
                <option value="100">100</option>
            </select>
        </div>
        <script src="/static/jquery-1.12.4.js"></script>
        <script src="/static/jquery.cookie.js"></script>
        <script>
            $(function () {
                var v = $.cookie('per_page_count');  /* 页面重新加载后获取该值,然后让select的val加载该值*/
                $('#ps').val(v)
            })
            function chanagePageSize(ths) {
                var v = $(ths).val();
                $.cookie('per_page_count',v,{path: '/user_list'})
                location.reload()
            }
        </script>
    </body>
    View Code
    def user_list(request):
        val = request.COOKIES.get('per_page_count')
        val = int(val)  #该值必须为整数
    View Code

            设置cookie可以使用密文设置:

            obj = HttpResponse('s')

            obj.set_signed_cookie('username','hahaha',salt='abcabcabd')  #设置cookie为密文

            获取cookie解密:

            request.get_signed_cookie('username',salt='abcabcabd')

        

          装饰器:

            - FBV:       

    def auth(func):
        def inner(*args,**kwargs):
            v = request.COOKIES.get('usernmae')
            if not v:
                return redirect('/login/')
            return func(request,*args,**kwargs)
        return inner
    
    @auth
    View Code

            - CBV

    def auth(func):
        def inner(*args,**kwargs):
            v = request.COOKIES.get('usernmae')
            if not v:
                return redirect('/login/')
            return func(request,*args,**kwargs)
        return inner
    
    
    from django import  views
    from django.utils.decorators import method_decorator
     class Order(views.View):
    
    
         @method_decorator(auth)   #只对get方法做认证
         def get(self,request):
             pass
    
         def post(self,request):
    只对get方法做认证
    def auth(func):
        def inner(*args,**kwargs):
            v = request.COOKIES.get('usernmae')
            if not v:
                return redirect('/login/')
            return func(request,*args,**kwargs)
        return inner
    
    
    from django import  views
    from django.utils.decorators import method_decorator
    @method_decorator(auth,name='dispath')
     class Order(views.View):
    
         def get(self,request):
             pass
    
         def post(self,request):
             pass
    CBV装饰器方法一
    def auth(func):
        def inner(*args,**kwargs):
            v = request.COOKIES.get('usernmae')
            if not v:
                return redirect('/login/')
            return func(request,*args,**kwargs)
        return inner
    
    from django import  views
    from django.utils.decorators import method_decorator
    
     class Order(views.View):
    
        @method_decorator(auth)
        def dispatch(self, request, *args, **kwargs):
            return super(Order, self).dispatch(request,*args,**kwargs)
         def get(self,request):
             pass
    
         def post(self,request):
             pass
    CBV装饰器方法二

       5、分页(自定义分页)

         防止XSS攻击:默认情况下django只会认为后端传递过来的是字符串,所以html标记、js语言全部当做字符串来处理

          为了让django可以接受html或者js语言,可以使用:

          1、前端方法:使用filter: {{ str|safe }}  //通过safe在前端将html、js转换

          2、后端方法:引用 from django.utils.safestring import mark_safe,然后将自定义字符串通过mark_safe方法进行处理

                

       6、Form验证

      

         

  • 相关阅读:
    python登录qq
    js加解密的算法
    python request模板
    qq查询接口
    python代理池的实现
    mvvm实现
    消息队列
    【Linux常见命令】seq命令
    【Linux常见命令】find命令
    【Linux常见命令】rm命令
  • 原文地址:https://www.cnblogs.com/xiaopi-python/p/7190427.html
Copyright © 2011-2022 走看看