参考:https://www.zmrenwu.com/post/53/

详细见参考

一般请求的判断方法:

  1. def view(request, *args, **kwargs):
  2. if request.method.lower() == 'get':
  3. do_something()
  4. if request.method.lower() == 'post':
  5. do_something()

使用View.as_view()代替判断:

  1. class ClassName(View):
  2. '''
  3. 继承View自动判断请求方法
  4. '''
  5. def post():
  6. pass
  7.  
  8. def get():
  9. pass
  10.  
  11. def other():
  12. pass
  13.  
  14. #调用方法
  15. url(url, ClassName.as_view(), name)

设计思想:把视图函数的逻辑定义到类的方法里面去,然后在函数中实例化这个类,通过调用类的方法实现函数逻辑,而把逻辑定义在类中的一个好处就是可以通过继承复用这些方法。

  1. class View(object):
  2. """
  3. Intentionally simple parent class for all views. Only implements
  4. dispatch-by-method and simple sanity checking.
  5. """
  6.  
  7. http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  8.  
  9. def __init__(self, **kwargs):
  10. """
  11. Constructor. Called in the URLconf; can contain helpful extra
  12. keyword arguments, and other things.
  13. """
  14. # Go through keyword arguments, and either save their values to our
  15. # instance, or raise an error.
  16. for key, value in six.iteritems(kwargs):
  17. setattr(self, key, value)
  18.  
  19. @classonlymethod
  20. def as_view(cls, **initkwargs):
  21. """
  22. Main entry point for a request-response process.
  23. """
  24. for key in initkwargs:
  25. if key in cls.http_method_names:
  26. raise TypeError("You tried to pass in the %s method name as a "
  27. "keyword argument to %s(). Don't do that."
  28. % (key, cls.__name__))
  29. if not hasattr(cls, key):
  30. raise TypeError("%s() received an invalid keyword %r. as_view "
  31. "only accepts arguments that are already "
  32. "attributes of the class." % (cls.__name__, key))
  33.  
  34. def view(request, *args, **kwargs):
  35. self = cls(**initkwargs)
  36. if hasattr(self, 'get') and not hasattr(self, 'head'):
  37. self.head = self.get
  38. self.request = request
  39. self.args = args
  40. self.kwargs = kwargs
  41. return self.dispatch(request, *args, **kwargs)
  42. view.view_class = cls
  43. view.view_initkwargs = initkwargs
  44.  
  45. # take name and docstring from class
  46. update_wrapper(view, cls, updated=())
  47.  
  48. # and possible attributes set by decorators
  49. # like csrf_exempt from dispatch
  50. update_wrapper(view, cls.dispatch, assigned=())
  51. return view
  52.  
  53. def dispatch(self, request, *args, **kwargs):
  54. # Try to dispatch to the right method; if a method doesn't exist,
  55. # defer to the error handler. Also defer to the error handler if the
  56. # request method isn't on the approved list.
  57. if request.method.lower() in self.http_method_names:
  58. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  59. else:
  60. handler = self.http_method_not_allowed
  61. return handler(request, *args, **kwargs)
  62.  
  63. def http_method_not_allowed(self, request, *args, **kwargs):
  64. logger.warning(
  65. 'Method Not Allowed (%s): %s', request.method, request.path,
  66. extra={'status_code': 405, 'request': request}
  67. )
  68. return http.HttpResponseNotAllowed(self._allowed_methods())
  69.  
  70. def options(self, request, *args, **kwargs):
  71. """
  72. Handles responding to requests for the OPTIONS HTTP verb.
  73. """
  74. response = http.HttpResponse()
  75. response['Allow'] = ', '.join(self._allowed_methods())
  76. response['Content-Length'] = ''
  77. return response
  78.  
  79. def _allowed_methods(self):
  80. return [m.upper() for m in self.http_method_names if hasattr(self, m)]

View类源码

django基类View.as_view()的更多相关文章

  1. 基类View

    尽管类视图看上去类的种类繁多,但每个类都是各司其职的,且从类的命名就可以很容易地看出这个类的功能.大致可分为如下三个大的功能块,分别由三个类提供对应的方法: 处理 HTTP 请求.根据 HTTP 请求 ...

  2. Django——基于类的视图(class-based view)

    刚开始的时候,django只有基于函数的视图(Function-based views).为了解决开发视图中繁杂的重复代码,基于函数的通用视图( Funcation-based generic vie ...

  3. django abstract base class ---- 抽象基类

    抽象蕨类用于定义一些同享的列.类本身并不会在数据库端有表与之对应 一.例子: 1.定义一个叫Person 的抽象基类.Student 继承自Person from django.db import m ...

  4. Django url中可以使用类视图.as_view()进行映射的原因

    说明:在练习天天生鲜项目时,对利用类视图去与正则匹配到的url做映射有点疑惑,经过查看他人博客以及自我分析算是整明白了,所以记录一下 参考:https://www.zmrenwu.com/post/5 ...

  5. django中抽象基类的Foreignkey的定义

    class base(models.Model): user = models.ForeignKey(User) class Meta: abstract =True 以上是抽象基类的定义,只有一个公 ...

  6. django(六):view和cbv

    FBV即以函数的形式实现视图函数,CBV即以类的形式实现视图函数:相比而言,CBV根据请求方式书写各自的代码逻辑,结构清晰明了,但是由于多了一层反射机制,性能要差一些:FBV执行效率要高一些,但是代码 ...

  7. Django——基于类的视图源码分析 二

    源码分析 抽象类和常用视图(base.py) 这个文件包含视图的顶级抽象类(View),基于模板的工具类(TemplateResponseMixin),模板视图(TemplateView)和重定向视图 ...

  8. DRF视图-基类

    2个视图基类 REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写. 为了区分上面请求和响应的代码,我们再次创建一个新的子应用: python manage.py star ...

  9. Django Function Based View(FBV)和Class Based View (CBV)对比

    一.FBV处理过程 首先来看一下FBV逻辑过程: 1.简单过程(借用官方示例): urls: from django.conf.urls import url from . import views ...

随机推荐

  1. WF控制台工作流(1)

    简单使用WF工作流示例: using System; using System.Linq; using System.Activities; using System.Activities.State ...

  2. 解决NO migrations to apply

    创建表之后,遇到models模型变动,故当时做了删除应用文件夹下migrations文件,删除后重建,但重建后执行模型合并操作结果为No Changes,无法创建数据表 执行python3 manag ...

  3. 基于Python的机器学习实战:AadBoost

    目录: 1. Boosting方法的简介 2. AdaBoost算法 3.基于单层决策树构建弱分类器 4.完整的AdaBoost的算法实现 5.总结 1. Boosting方法的简介 返回目录 Boo ...

  4. Linux RPM、YUM、APT包管理工具

    ⒈rpm包的管理 1)介绍 rpm是一种用于互联网下载包的打包及安装工具,它包含在某些Linux分发版中,它生成具有.RPM扩展名的文件,RPM是RedHat Package Manager(RedH ...

  5. Linux注销&登陆

    ⒈注销 ①在命令行使用logout,此指令在图形界面无效.

  6. 转载CSDN博客步骤

    在参考“如何快速转载CSDN中的博客”后,由于自己不懂html以及markdown相关知识,所以花了一些时间来弄明白怎么转载博客,以下为转载CSDN博客步骤和一些知识小笔记. 参考博客原址:http: ...

  7. 【转】Windows下安装python2和python3双版本

    [转]Windows下安装python2和python3双版本 现在大家常用的桌面操作系统有:Windows.Mac OS.ubuntu,其中Mac OS 和 ubuntu上都会自带python.这里 ...

  8. 异步编程之使用yield from

    异步编程之使用yield from yield from 是 Python3.3 后新加的语言结构.yield from的主要功能是打开双向通道,把最外层的调用方法与最内层的子生成器连接起来.这两者就 ...

  9. Python3学习笔记12-定义函数及调用

    函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段,能提高应用的模块性,和代码的重复利用率 Python提供了许多内建函数,比如print().也可以自己创建函数,这被叫做用户自定义函数 ...

  10. 如何理解深度学习中的Transposed Convolution?

    知乎上的讨论:https://www.zhihu.com/question/43609045?sort=created 不过看的云里雾里,越看越糊涂. 直到看到了这个:http://deeplearn ...