Django View类的解析
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类的解析的更多相关文章
- Django——基于类的视图(class-based view)
刚开始的时候,django只有基于函数的视图(Function-based views).为了解决开发视图中繁杂的重复代码,基于函数的通用视图( Funcation-based generic vie ...
- PureMVC(JS版)源码解析(九):View类
在讲解View类之前,我们先回顾一下PureMVC的模块划分: 在PureMVC中M.V.C三部分由三个单例类管理,分别是Model/View/Controller.PureMVC中另外一个 ...
- django基类View.as_view()
参考:https://www.zmrenwu.com/post/53/ 详细见参考 一般请求的判断方法: def view(request, *args, **kwargs): if request. ...
- Django View(视图系统)
Django View 官方文档 一个视图函数(类),简称视图,是一个简单的 Python 函数(类),它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误 ...
- Django View视图
视图view 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应.响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者 ...
- Django APIView源码解析
APIView使用:luffy项目中关于APIView的使用 在Django之 CBV和FBV中,我们是分析的from django.views import View下的执行流程,以下是代码 fro ...
- Thinkphp源码分析系列(九)–视图view类
视图类view主要用于页面内容的输出,模板调用等,用在控制器类中,可以使得控制器类把表现和数据结合起来.下面我们来看一下执行流程. 首先,在控制器类中保持着一个view类的对象实例,只要继承自控制器父 ...
- Django Rest framework 之 解析器
RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...
- CBV流程之View源码解析
CBV是基于反射实现根据请求方式不同,执行不同的方法. 请求流程:view源码解析 1.urls.py :请求一定来执行视图下的as_view方法.也可以直接点击as_view()来找源码. 2.vi ...
随机推荐
- 【Todo】Java的JIT机制
先是参考了这篇说的不怎么详细的文章<Java的JIT机制>(Link) JIT是just in time,即时编译技术.使用该技术,能够加速java程序的执行速度. 通常javac将程序源 ...
- 梯度下降和EM算法,kmeans的em推导
I. 牛顿迭代法给定一个复杂的非线性函数f(x),希望求它的最小值,我们一般可以这样做,假定它足够光滑,那么它的最小值也就是它的极小值点,满足f′(x0)=0,然后可以转化为求方程f′(x)=0的根了 ...
- 【paddle学习】识别数字
Softmax回归(Softmax Regression) 最简单的Softmax回归模型是先将输入层经过一个全连接层得到的特征,然后直接通过softmax 函数进行多分类 输入层的数据$X$传到输出 ...
- BUPT复试专题—统计时间间隔(2013计院)
题目描述 给出两个时间(24小时制),求第一个时间至少要经过多久才能到达第二个时间.给出的时间一定满足的形式,其中x和y分别代表小时和分钟.0≤x<24,0≤y<60. 输入格式 第一行为 ...
- Html5培训之精髓
一.核心技术(可去各技术官网学习) 1.html5的六大核心技术:Html5,CSS3,JavaScript,WebSocket,PhoneGap,Node.js,它们覆盖了设备端,浏览器端和云端的开 ...
- 在linux中安装.sh 文件
有一些linux的安装包是.sh后缀的安装包,可以通过$bash xxx.sh的命令来进行安装.
- poj2406--Power Strings(kmp:求循环串的次数)
Power Strings Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 33163 Accepted: 13784 D ...
- ios开发之自己定义默认生成的导航栏 标题 颜色 返回button
一 改动导航栏颜色 导航栏在哪个页面代码放在那里面 self.navigationController.navigationBar.tintColor = [UIColor colorWithR ...
- HDU 5371 Hotaru's problem(Manacher算法+贪心)
manacher算法详见 http://blog.csdn.net/u014664226/article/details/47428293 题意:给一个序列,让求其最大子序列,这个子序列由三段组成, ...
- 如何理解pca和svd的关系?
主成分分析和奇异值分解进行降维有何共同点? 矩阵的奇异值分解 当矩阵不是方阵,无法为其定义特征值与特征向量,可以用一个相似的概念来代替:奇异值. 通常用一种叫奇异值分解的算法来求取任意矩阵的奇异值: ...