view() :

    该类为所有类视图的父类,处于最底层,仅仅只对请求参数做校验后,给特定请求方法做特定调用。

用法:

url中定位到类方法:Aa.as_view() ——> View.as_view()方法对请求参数做判断后,转到View.dispatch() ——> 找到Aa.get() 或者Aa.post() 或者Aa.其他请求方法 ———>处理完成后返回view()

    需要对请求方式做特定处理,可以自行修改dispatch()方法。

 

源码:

  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. """
  8. # http 所有请求方式的列表
  9. http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  10. def __init__(self, **kwargs):
  11. """
  12. Constructor. Called in the URLconf; can contain helpful extra
  13. keyword arguments, and other things.
  14. # 构造函数接收键值对参数,该参数来源于 URLconf配置中的传递
  15. """
  16. # Go through keyword arguments, and either save their values to our
  17. # instance, or raise an error.
  18. # 接收关键字参数,并将其添加到实例中或者引发错误
  19. for key, value in six.iteritems(kwargs):
  20. setattr(self, key, value)
  21. @classonlymethod
  22. def as_view(cls, **initkwargs):
  23. """
  24. # as_view 是一个闭包,做了一些校验工作后,再返回view函数
  25. Main entry point for a request-response process.
  26. """
  27. for key in initkwargs:
  28. #as_view()方法中,如果传递的关键字参数key为默认的http 请求方法,则报错,
  29. #默认不允许使用http请求方法作为参数
  30. if key in cls.http_method_names:
  31. raise TypeError("You tried to pass in the %s method name as a "
  32. "keyword argument to %s(). Don't do that."
  33. % (key, cls.__name__))
  34. # as_view()方法中,如果传递过来的参数key 不在as_view()的属性中,也报错
  35. if not hasattr(cls, key):
  36. raise TypeError("%s() received an invalid keyword %r. as_view "
  37. "only accepts arguments that are already "
  38. "attributes of the class." % (cls.__name__, key))
  39. # view 方法作用是给请求对象添加三个参数,调用dispatch方法处理请求
  40. def view(request, *args, **kwargs): # 作用:增加属性,调用dispatch方法
  41. self = cls(**initkwargs) # 调用as_view 父类,创建一个实例对象
  42. # 如果对象中有get属性,或者没有head属性,就创建head属性
  43. if hasattr(self, 'get') and not hasattr(self, 'head'):
  44. self.head = self.get
  45. # 为对象创建request、args和kwargs 三个属性
  46. self.request = request
  47. self.args = args
  48. self.kwargs = kwargs
  49. #调用dispatch 函数找到指定的请求方法,
  50. return self.dispatch(request, *args, **kwargs)
  51. view.view_class = cls
  52. view.view_initkwargs = initkwargs
  53. # take name and docstring from class
  54. update_wrapper(view, cls, updated=())
  55. # and possible attributes set by decorators
  56. # like csrf_exempt from dispatch
  57. update_wrapper(view, cls.dispatch, assigned=())
  58. return view
  59. # 找到请求的方法,执行该方法
  60. def dispatch(self, request, *args, **kwargs):
  61. # Try to dispatch to the right method; if a method doesn't exist,
  62. # defer to the error handler. Also defer to the error handler if the
  63. # request method isn't on the approved list.
  64. # 找到请求的方法,如果请求方法不在允许的列表中或者请求方法不存在就按照错误处理
  65. # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  66. # 如果请求方法存在,则取出该方法
  67. if request.method.lower() in self.http_method_names:
  68. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  69. # 如果不存在则报405错误
  70. else:
  71. handler = self.http_method_not_allowed
  72. # 执行该请求方法
  73. return handler(request, *args, **kwargs)
  74. def http_method_not_allowed(self, request, *args, **kwargs):
  75. logger.warning(
  76. 'Method Not Allowed (%s): %s', request.method, request.path,
  77. extra={'status_code': 405, 'request': request}
  78. )
  79. return http.HttpResponseNotAllowed(self._allowed_methods())
  80. def options(self, request, *args, **kwargs):
  81. """
  82. Handles responding to requests for the OPTIONS HTTP verb.
  83. """
  84. response = http.HttpResponse()
  85. response['Allow'] = ', '.join(self._allowed_methods())
  86. response['Content-Length'] = '0'
  87. return response
  88. def _allowed_methods(self):
  89. return [m.upper() for m in self.http_method_names if hasattr(self, m)]

   用法实例:

  1. class LoginUserView(View):
  2. def dispatch(self, request, *args, **kwargs):
  3. print "进入了改写后的dispatch方法"
  4. discontext = super(LoginUserView, self).dispatch(request, *args, **kwargs)
  5. print "没有改变调用请求方式,直接返回原始dispatch调用"
  6. return discontext
  7. def post(self, request):
  8. context = userservice.login_user(request=request)
  9. return JsonResponse(context)

  

ListView() :

    

django 类通用视图详解的更多相关文章

  1. ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解

    原文 ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 ...

  2. 【译】ASP.NET MVC 5 教程 - 7:Edit方法和Edit视图详解

    原文:[译]ASP.NET MVC 5 教程 - 7:Edit方法和Edit视图详解 在本节中,我们继续研究生成的Edit方法和视图.但在研究之前,我们先将 release date 弄得好看一点.打 ...

  3. 【转】UML类图与类的关系详解

    UML类图与类的关系详解   2011-04-21 来源:网络   在画类图的时候,理清类和类之间的关系是重点.类的关系有泛化(Generalization).实现(Realization).依赖(D ...

  4. String类的构造方法详解

    package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...

  5. [转]c++类的构造函数详解

    c++构造函数的知识在各种c++教材上已有介绍,不过初学者往往不太注意观察和总结其中各种构造函数的特点和用法,故在此我根据自己的c++编程经验总结了一下c++中各种构造函数的特点,并附上例子,希望对初 ...

  6. Scala 深入浅出实战经典 第63讲:Scala中隐式类代码实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...

  7. UML类图与类的关系详解

    摘自:http://www.uml.org.cn/oobject/201104212.asp UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类 ...

  8. phpcms加载系统类与加载应用类之区别详解

    <?php 1. 加载系统类方法load_sys_class($classname, $path = ''", $initialize = 1)系统类文件所在的文件路径:/phpcms ...

  9. c++类的构造函数详解

    c++类的构造函数详解 一. 构造函数是干什么的 class Counter{ public:         // 类Counter的构造函数         // 特点:以类名作为函数名,无返回类 ...

随机推荐

  1. Jquery radio选中

    radio选中$("input[name=test][value=34]").attr("checked",true);//value=34的radio被选中$ ...

  2. Error:Execution failed for task ‘:app:processDebugManifest’.

    Error:Execution failed for task ':app:processDebugManifest'. > Manifest merger failed : Attribute ...

  3. Restful Web Service部署到weblogic 12c

    介绍一下环境: 首先需要下载一个jaxrs-ri-2.22.2.zip的包 采用Jdeveloper 12c版本,jdk1.8 WebLogic Server 12.2.1版本 Restful项目建立 ...

  4. npm依赖管理:冗余,依赖树

    npm的依赖树查询:原理都是查询文件夹node_modules的结构.比如mac的node_modules位置在/usr/local/lib下.具体项目的node_modules位置位于项目根目录下. ...

  5. Delphi 7下最小化到系统托盘

    在Delphi 7下要制作系统托盘,只能制作一个比较简单的系统托盘,因为ShellAPI文件定义的TNotifyIconData结构体是比较早的版本.定义如下: 123456789   _NOTIFY ...

  6. FL2440 rt3070模块station模式动态获取IP地址

    ---------------------------------------------------------------------------------------------------- ...

  7. Solr json,xml等文件数据导入(添加索引)linux下操作

    使用solr-5.3.1\example\exampledocs下的post.jar来完成数据导入 1.将想要导入的文件放在solr-5.3.1\example\exampledocs中,如aaa.x ...

  8. 查看进程id, 父进程id _How do I get the parent process ID of a given child process?

    How to get parent pid from a given children pid? I know I can mannully check it under /proc, I am wo ...

  9. 作为Java程序员应该掌握的10项技能

    本文详细罗列了作为Java程序员应该掌握的10项技能.分享给大家供大家参考.具体如下: 1.语法:必须比较熟悉,在写代码的时候IDE的编辑器对某一行报错应该能够根据报错信息知道是什么样的语法错误并且知 ...

  10. hibernate学习系列-----(6)hibernate对集合属性的操作之Set集合篇

    先说一段废话吧,本打算每天把所学的知识总结为博客的,但是昨天为什么没有写呢?没有学习吗?No,那是为什么?贪玩,对,这位同学说对了,老实说昨天感觉身体不怎么舒服,大家都知道,这其实就是为自己懒找借口, ...