class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
""" http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr(self, key, value) @classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs # take name and docstring from class
update_wrapper(view, cls, updated=()) # and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs) def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return http.HttpResponseNotAllowed(self._allowed_methods())

View类的部分源码如上所示。那么平时使用 类 类型的视图是如何解析的呢,下面进行简单介绍:

在url中通常有如下代码

------------------------------------------------------------------------------------------------------------------------------------------------------------->

urlpatterns=[

url(r'^$',SomeView.as_view(),name='index'),

url(r'^about/$',AboutView.as_view(),name='about'),

]

------------------------------------------------------------------------------------------------------------------------------------------------------------->

当有人访问我们的网站根目录的时候,url会在url列表中进行匹配,找到第一个匹配项则把对应的request和其他参数传递给对应的视图

那么在上面的urlpatterns中则一定会匹配到第一条,也就是会把request等信息传递给SomeView.as_view()方法。因为SomeView继承自View,而我们没有去实现as_view()方法

,那么也就是View.as_view()会进行处理。

而处理的过程如下,解释标注在下面代码中:

 @classonlymethod

    def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
for key in initkwargs: #首先是判断 在urlpatterns中as_view有没有传入 http方法的参数,比如我传入一个 get='post',
if key in cls.http_method_names: #如果传入了呢,则会抛出异常,
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key): #如果传入的参数并不存在于 视图类中,比如我传入 temp='123',而我的视图类中并没有该属性,也会抛出异常
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): #此方法主要用于返回请求的 视图
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):#如果类视图实现了 get方法,并且没实现head方法,则head方法等同于get方法
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs) #这是查找类视图中对应方法的重要步骤
view.view_class = cls
view.view_initkwargs = initkwargs # take name and docstring from class
update_wrapper(view, cls, updated=()) # and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view #把最终的视图处理返回用于调用

------------------------------------------------------------------------------------------------------------------------------------------------------------->

dispatch解释标注在下面代码中

    def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:#判断request中的方法是不是类视图允许的方法
#如果是允许的方法,则会在对应的类视图中的方法传给给handler用于之后的处理
  #如果是允许的方法,但是类视图中没有实现该方法,则把http_method_not_allowed方法返回
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:#是不允许的方法,则返回 http_method_not_allowed方法,源码在开头
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)

欢迎大家批评指正

Django View类的解析的更多相关文章

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

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

  2. PureMVC(JS版)源码解析(九):View类

    在讲解View类之前,我们先回顾一下PureMVC的模块划分:      在PureMVC中M.V.C三部分由三个单例类管理,分别是Model/View/Controller.PureMVC中另外一个 ...

  3. django基类View.as_view()

    参考:https://www.zmrenwu.com/post/53/ 详细见参考 一般请求的判断方法: def view(request, *args, **kwargs): if request. ...

  4. Django View(视图系统)

    Django View 官方文档 一个视图函数(类),简称视图,是一个简单的 Python 函数(类),它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误 ...

  5. Django View视图

    视图view 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者 ...

  6. Django APIView源码解析

    APIView使用:luffy项目中关于APIView的使用 在Django之 CBV和FBV中,我们是分析的from django.views import View下的执行流程,以下是代码 fro ...

  7. Thinkphp源码分析系列(九)–视图view类

    视图类view主要用于页面内容的输出,模板调用等,用在控制器类中,可以使得控制器类把表现和数据结合起来.下面我们来看一下执行流程. 首先,在控制器类中保持着一个view类的对象实例,只要继承自控制器父 ...

  8. Django Rest framework 之 解析器

    RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...

  9. CBV流程之View源码解析

    CBV是基于反射实现根据请求方式不同,执行不同的方法. 请求流程:view源码解析 1.urls.py :请求一定来执行视图下的as_view方法.也可以直接点击as_view()来找源码. 2.vi ...

随机推荐

  1. 完整的MVC框架(前端、后台和数据库)

    终于学完了数据库的连接,可以做一个完整的项目了,以前做的练习都没有关联到数据库,没法进行事务. MVC框架 先上图: 老师画的图,有点乱,但是大概意思还是可以理解. 这个练习是简单的存储一个学生读了哪 ...

  2. BUPT复试专题—奇偶求和(2014软件)

    题目描述 给出N个数,求出这N个数,奇数的和以及偶数的和. 输入 第一行为测试数据的组数T(1<=T<=50).请注意,任意两组测试数据之间是相互独立的. 每组数据包括两行: 第一行为一个 ...

  3. 基于源码学习-fighting

    今天逛着逛着,看到个培训网站,点进去和客服人员聊了一下.接着,看了看他们的培训课程,想了解一下 嵌入式开发的. (人就是要放空自己,把自己当做什么都不会,当着个婴儿[小学生]一般认真,要学什么知识就是 ...

  4. 转: memcache, redis, mongodb 对比

    http://db-engines.com/en/system/Memcached%3BMongoDB%3BRedis

  5. PHP-MySQL,PHP-MySQLi,PDO的差异

    PHP-MySQL是PHP操作MySQL数据库最原始的Extension ,PHP-MySQLi的i代表Improvement ,提供了更加高级的功能,就Extension而言,本身也增加了安全性.而 ...

  6. openwrt procd

    接着前面写过的一篇关于 procd 的笔记. procd 在 STATE_INIT 时会运行 /etc/inittab 中描述的几个级别指定程序. procd_inittab_run("re ...

  7. appium安装报错但运行成功

    npm install -g  appium ERR! fetch failed https://registry.npmjs.org/appium-uiauto/-/appium-uiauto-1. ...

  8. Direct3D 9 入门样例程序 圆锥体

    介绍 Directx3D 9 什么是DirectX,非常好说了,Win32 C++ API.主要是多媒体编程方面的,长处体如今高性能了,如今我知道的版本号最高是D3D11,可是我是学习入门的,从D3D ...

  9. 关闭mongodb 集群

    [root@hadoop1 ~]# ps -aux | grep mongodb; root ? Sl : : /usr/local/mongodb/bin/mongod -f /usr/local/ ...

  10. hdfs 3种 通讯协议

    http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_design.html 通讯协议 所有的HDFS通讯协议都是建立在TCP/IP协议之上.客户端通过一个可配置的 ...