zoukankan      html  css  js  c++  java
  • Django中的装饰器和万能的点

    前言

      好朋友陈道远是个爱美的人,就算裸奔也是把自己洗的白白的,总是想着装饰自己,他每天出门都要打扮自己,可是在每次都会进行很多重复的东西,这时候他来问李阳,李阳告诉他至于要把重复的动作制作一个套,每次出去带上套,只要添加今天需要的东西就好,为了感谢李阳,他就和李阳一起唱起了拼刺刀,他夸赞李阳厉害,到胃了,他走的时候问李阳要朵花,李阳告诉他,:你送来的菊花,我已经让他变成了玫瑰!    本节来讲Django中的装饰器,没有万能的道远,但是有万能的点.
    

    Django的视图函数view

    request对象

    就是从前端打交道的关键字      models是与数据库打交道的关键字  这是最通俗易懂的理解
    

    respanse对象

    render 回复html页面
    redirect 重定向
    HttpResponse   回复字符串
    

    装饰器:

    def func(f):
      def inner(request):
        print("被装饰前")
        ret=f(request)
        print("被装饰之后")
        return ret
      return inner
    #在FBV模式下,和普通函数加装饰器是一样的写法
    @func
    def hong(request):
      print('home')
      return HttpResponse('你好,老板,,,,要多少钱的')
    CBV加装饰的三个姿势:
        # @method_decorator(func,name='get') 位置3
        class LoginView(View):
            # @method_decorator(func) #位置2
            def dispatch(self, request, *args, **kwargs):
                print('aaaa')
                ret = super().dispatch(request, *args, **kwargs) #render(request, 'login.html')
                print('bbbb')
                return ret
            @method_decorator(func)  #位置1
            def get(self,request):
                print('this is get method!!!')
                return render(request, 'login.html')
    
            def post(self,request):
                uname = request.POST.get('username')
                pwd = request.POST.get('password')
                if uname == 'alex' and pwd == 'dsb':
                    return redirect('/home/')
                else:
                    return redirect('/login/')
    
    
    
    FBV:function based view 基于函数的视图函数
    例子:
    def login(request):
        if request.method=='GET':
             return render(request,'login.html')
        else:
             user=request.POST.get('username')
             pwd=request.POST.get('password')
             if user=='alex' and pwd=='dsb':
                return redirect('/home/')
             else:
              return render(request,'login.html')
    #
    
    路经:
       url(r'^login/', views.Login),
    

    CBV:class based view  基于类的视图函数
    例子:
    from django.views import View
    
    class LoginView(View):
    
    ​    def get(self,request):
    ​        return render(request, 'login.html')
    
    ​    def post(self,request):
    ​        uname = request.POST.get('username')
    ​        pwd = request.POST.get('password')
    
    ​        if uname == 'alex' and pwd == 'dsb':
    ​            return redirect('/home/')
    ​        else:
    ​            return redirect('/login/')
       路经:
    
        url(r'^login/', views.LoginView.as_view()),
    

    模板渲染

    {{变量}}   {%逻辑%}
    

    万能的点

    <h1>{{nam}}</h1>
    <h1>{{s}}</h1>
    <h1>{{11.1}}</h1>
    <h1>{{d1.number}}</h1>
    <h1>{{a.yue}}</h1>
    <h1>{{a.xx}}</h1>
    
    
    view.py的写法
    def home(request):
    
        num = 100
        s = 'hello my girl I love you'
        l1 = [11,22,33]
        d1 = {'name':'冠希哥','number':1000}
        class A:
            balance = 2000
            def __init__(self):
                self.xx = 'oo'
            def yue(self):
                return 'how much!'
        a = A()
        # render({'xx':'oo'})
        return render(request,'home.html',{'num':num,'s':s,'l1':l1,'d1':d1,'a':a})
    
    
    
    
    
    

    静态函数配置

    过滤器用法 {{ 变量|过滤器名称:'参数' }}  ,不是所有过滤器都有参数,如果没参数的话写法:{{ 变量|过滤器名称 }}
    
    <h1>{{ s|truncatechars:n }}</h1> 过滤器里面的参数都可以写后端返回的变量
    
    default -- <h1>{{ xx|default:'抱歉,没有数据!!' }}</h1> #默认值
    length  -- <h1>{{ l1|length }}</h1>  获取变量数据长度
    filesizeformat -- <h2>{{ file_size|filesizeformat }}</h2> #大小按照人类可读的显示
    slice -- <h2>{{ s|slice:'0:7' }}</h2> #切片 顾头不顾腚
    date: -- <h3>{{ now|date:'Y-m-d H:i:s' }}</h3>  #日期格式化显示
    safe -- <h1>{{ a_tag|safe }}</h1> 数据:    a_tag = "<a href='http://www.baidu.com'>百度</a>"
    	safe介绍
        Django的模板中在进行模板渲染的时候会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全,django担心这是用户添加的数据,比如如果有人给你评论的时候写了一段js代码,这个评论一提交,js代码就执行啦,这样你是不是可以搞一些坏事儿了,写个弹窗的死循环,那浏览器还能用吗,是不是会一直弹窗啊,这叫做xss攻击,所以浏览器不让你这么搞,给你转义了。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。
    truncatechars -- <h1>{{ s|truncatechars:'6' }}</h1>
        
    join -- <h1>{{ l1|join:'+' }}</h1>
    

    url斜杠

    url(r'^home/', views.home),  #前置导航斜杠不需要写,后面的斜杠是根据django的配置来的,如果在settings配置文件中我们设置了
    # APPEND_SLASH = False,那么浏览器发送来的请求如果没有带着后面的斜杠,也是可以正常请求的,但是如果没有这个配置的话,django要求浏览器必须带着路径后面的斜杠来进行访问,如果你输入路径的时候没有加/,那么django让你的浏览器发一个重定向请求带上/.
    

    静态文件配置

    在项目中,其实jscssjgp图片等等都称为静态文件.
    在django中的使用
    1 配置,在settings配置文件中写上以下配置
    
    STATIC_URL = '/static/' #127.0.0.1:8000/static/bootstrap/css.
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR,'jingtaiwenjianjia'),
    ]
    
    2 html文件中使用
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">  相对路径引入静态文件时,前置斜杠必须加上,不管是什么,a标签也是一样,相对路径访问,必须前面的斜杠
    	
    
    from django.views import View
    
    class book_list(View):
        def get(self,request):
            all_books = models.Book.objects.all()  # 对象列表
            return render(request, 'book_list.html', {'all_books': all_books})
    class book_del(View):
        def get(self,request):
            pk = request.GET.get('id')
            models.Book.objects.filter(pk=pk).delete()
            return redirect('/book_list/')
    
    class book_add(View):
        def get(self,request):
            return render(request, 'book_add.html')
        def post(self,request):
            book_name = request.POST.get('book_name')
            book_price = request.POST.get('book_price')
            publisher_name = request.POST.get('publisher_name')
            publish_time = request.POST.get('publish_time')
    
            if models.Book.objects.filter(book_name=book_name):
                error = '书名已经存在'
    
            else:
                models.Book.objects.create(book_name=book_name, book_price=book_price, publisher_name=publisher_name,
                                           publish_time=publish_time)
                return redirect('/book_list/', {'error': error})
    
    class book_edi(View):
        def get(self,request):
            pk = request.GET.get('id')
            book_obj = models.Book.objects.filter(pk=pk).first()
            return render(request, 'book_edi.html', {'book_obj': book_obj})
        def post(self,request):
            pk = request.GET.get('id')
            book_obj = models.Book.objects.filter(pk=pk).first()
            book_name = request.POST.get('book_name')
            book_price = request.POST.get('book_price')
            publisher_name = request.POST.get('publisher_name')
            publish_time = request.POST.get('publish_time')
    
            book_obj.book_name = book_name
            book_obj.book_price = book_price
            book_obj.publisher_name = publisher_name
            book_obj.publish_time = publish_time
            book_obj.save()
            return redirect('/book_list/')
    
    
    
    def reserch(request):
        ret = models.Book.objects.all().first()
    
    
        print(ret)
    
        return render(request,'reserch.html',{'ret':ret})
    
  • 相关阅读:
    has a / is a 的区别
    Linux头文件作用
    转一篇Decorator模式的讲解文章
    歌手推荐kate st. john
    拷贝构造函数和赋值构造函数声明为私有的作用
    重新认识C++中new的用法
    系统程序员成长计划容器与算法(二)(下)
    深入C++的new
    歌手推荐Cara Dillon
    浅析一道C++设计面试题
  • 原文地址:https://www.cnblogs.com/x-h-15029451788/p/11922507.html
Copyright © 2011-2022 走看看