django_day03

django_day03

Django的view(视图)

  1. CBV和FBV

    1. FBV:function based view 基于函数的视图

    2. CBV:class based view 基于类的视图

      from django.views import View
      
      class  Xxx():
          def get(self,request):
              #专门处理get请求
              return response
          def post(self,request):
              #专门处理post请求
              return response
          
      
      url(r'xx/',Xxx.as_view())
      
      class PublisherAdd(View):
      
          def get(self,request):
              print("get请求被执行")
              #处理get请求
              return render(request, 'publisher_add.html')
      
          def post(self,request):
              print("post请求被执行")
              #处理post请求
              pub_name = request.POST.get('pub_name')
              #print(pub_name)
              if not pub_name:
                  # 输入为空
                  return render(request, 'publisher_add.html', {'error': '不能为空!!'})
              if models.Publisher.objects.filter(name=pub_name):
                  return render(request, 'publisher_add.html', {'error': '已存在!'})
              ret = models.Publisher.objects.create(name=pub_name)
              #print(ret, type(ret))
              return redirect('/publisher_list/')
      
      urlpatterns = [
          url(r'^publisher_add/', views.PublisherAdd.as_view()),
          ]
      

      as_view流程

      1. 项目运行时加载urls.py的文件 执行类as_view方法

      2. as_view()执行后 内部定义了一个view函数 并且返回

      3. 请求到来的时候,执行view函数:

        1. 实例化类--》self

        2. self.request = request

        3. 执行self.dispatch(request, *args, **kwargs)的方法

          1. 判断请求方式是否被允许

            1. 允许:

              通过反射获取请求方式对应的请求方法 ——》 handler

              获取不到 self.http_method_not_allowed ——》 handler

            2. 不允许:

              self.http_method_not_allowed ——》 handler

          2. 执行handler,返回结果

      from functools import wraps
      
      def timer(func):
          @wraps(func)#不加的话获取的方法一直时inner   wraps原理
          def inner(request, *args, **kwargs):
              
              start = time.time()
              ret = func(request, *args, **kwargs)
              print('执行的时间是:{}'.format(time.time() - start))
              return ret
      
          return inner
      

      FBV

      直接加在函数上就行

      CBV加装饰器:

      需要使用一个装饰器

      from django.utils.decorators import method_decorator
      
      1. 加在方法上

        @method_decorator(timer)
        def get(self, request):
        
      2. 加在dispatch方法上

        @method_decorator(timer)
        def dispatch(self, request, *args, **kwargs):
            # 之前的操作
            ret = super().dispatch(request, *args, **kwargs)  # 执行View中的dispatch方法
            # 之后的操作
            return ret3
        
        @method_decorator(timer,name='dispatch')
        class PublisherAdd(View):
        
      3. 加在类上

        @method_decorator(timer,name='post')
        @method_decorator(timer,name='get')
        class PublisherAdd(View):
        

      request

      request.method  请求方法  GET POST 
      request.GET    URL上携带的参数   ?k1=v1&k2=v2   { }
      request.POST  post请求提交的数据  {}     编码方式是URLencode
      request.path_info  路径信息   不包含IP和端口 也不包含参数
      request.body  请求体   bytes类型  #post请求才有 数据
      request.COOKIES   cookie
      request.session    session
      request.FILES   长传的文件
      request.META    头的信息     小写——》大写   HTTP_ 开头   -  ——》 _
      
      request.get_full_path()  完整的路径信息  不包含IP和端口 包含参数
      request.is_ajax()    请求是否是ajax请求
      
      

      response

      from django.shortcuts import render, HttpResponse, redirect
      
      HttpResponse('字符串')  #   返回字符串
      render(request,'模板的文件名',{'k1':v1})   # 返回一个HTML页面
      redirect('地址')  # 重定向  Location:‘地址’  301 302 
      
      from django.http.response import JsonResponse
      JsonResponse({'k1':'v1'})
      JsonResponse(data,safe=False)
      

      上传文件

      urls.py

      url(r'^upload/', views.Upload.as_view()),
      

      视图:

      class Upload(View):
      
          def get(self, request):
              return render(request, 'upload.html')
          def post(self, request):
              file = request.FILES.get('f1')
              with open(file.name, 'wb') as f:
                  for i in file:
                      f.write(i)
              return HttpResponse('ok')
      

      upload.html

      <form action="" method="post" enctype="multipart/form-data">
          {% csrf_token %}
      
          <input type="file" name="f1">
          <button>上传</button>
      </form>
      

猜你喜欢

转载自www.cnblogs.com/DemoLi/p/12770018.html
今日推荐