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 ...
随机推荐
- PostgreSQL触发器的使用
原文: https://www.yiibai.com/postgresql/postgresql-trigger.html -------------------------------------- ...
- 怎样改动X-code中的字体大小、颜色
- Golang之bytes.buffer
bytes.buffer是一个缓冲byte类型的缓冲器存放着都是byte Buffer 是 bytes 包中的一个 type Buffer struct{-} A buffer is a variab ...
- 一场由股票提醒助手插件引发的血案——浅入浅出 jquery autocomplete
我没有学过前端,所以这篇文章注定要班门弄斧了. 通常,须要用到什么技术什么语言时,我才去学,学了也不一定掌握,就是记不住!所以如今明确了.学习的时候,亦或是攻克难点的时候,一定要记录下来.并不一定非要 ...
- 怎样使用ListView?
怎样使用ListView? watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFC ...
- Android中View的事件分发机制——Android开发艺术探索笔记
原文链接 http://sparkyuan.me/ 转载请注明出处 介绍 点击事件的事件分发就是对MotionEvent事件的分发过程.当一个MotionEvent产生了以后,系统须要把这个事件传递给 ...
- 进程-IPC 管道 (一)
详见:https://github.com/ZhangzheBJUT/linux/blob/master/IPC(%E4%B8%80).md 一 IPC 概述 进程间通信就是在不同进程之间传播或交换信 ...
- YTUOJ-推断字符串是否为回文
题目描写叙述 编敲代码,推断输入的一个字符串是否为回文.若是则输出"Yes",否则输出"No".所谓回文是指順读和倒读都是一样的字符串. 输入 输出 例子输入 ...
- 利用WebViewJavascriptBridge与UIWebView进行交互
事情的起因还是因为项目需求驱动.折腾了两天,由于之前没有UIWebView与JS交互的经历,并且觉得这次在功能上有一定的创造性,特此留下一点文字,方便日后回顾. 我要实现这样一个需求:按照本地的CSS ...
- 解决ubuntu10.04不能上网
1:命令行输入:lspci查看驱动,最后几行如果有ethernet controller:atheros communications ar8151 v1.0*的话,就说明驱动没有安装好, 2:下载地 ...