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>

最新文章

  1. Intent属性详解三 data、type和extra
  2. 【转】Java中try catch finally语句中含有return语句的执行情况(总结版)
  3. 优酷、YouTube、Twitter及JustinTV视频网站架构设计笔记
  4. 【M17】考虑使用缓式评估
  5. string的操作
  6. Nothing
  7. ADO。net学习笔记
  8. showmemory.c 和 hello.s 源码
  9. Ubuntu server 16.04安装,无网卡驱动解决
  10. Java中Sax解析XML
  11. Unity5 Shader Stripping 导致 LightMap 全部丢失的解决方法
  12. 关于RAS加密中pfx格式提取字符串私钥 (转)
  13. 20145214 《Java程序设计》第2周学习总结
  14. mysql无法输入中文排错
  15. 我的npm笔记
  16. JSON之—— JSON.parse()和JSON.stringify() (插曲)
  17. 如何打造你的独特观点(一) ——形成“自己的想法”的基础课zz
  18. uwsgi 热启动
  19. 在JavaScript中&quot;+&quot;什么时候是链接符号,什么时候是加法运算?
  20. oracle 行转列函数pivot和unpivot

热门文章

  1. javaweb获取客户端真实ip
  2. re学习笔记
  3. 命令行工具tabby--gi t仓库Token的使用
  4. ssh空闲一段时间后自动断网
  5. 一次 Keepalived 高可用的事故,让我重学了一遍它!
  6. Identity Server 4资源拥有者密码认证控制访问API
  7. Java开发学习(十二)----基于注解开发依赖注入
  8. 如何用全国天气预报API接口进行快速开发
  9. 【Unity基础知识】基础游戏单位GameObject中常用的属性和API
  10. 音响音箱/恒温壶/电量显示/电子数字时钟等LED数码管显示驱动IC-VK1640B 8段12位/12段8位显示