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 ...
随机推荐
- time is always a factor, time is always now!!!!
https://www.linkedin.com/pulse/time-always-now-joe-alderman ---------------------------------------- ...
- 数组遍历 map()、forEach() 及 字符串切割 split() / 字符串截取 slice()、substring()、substr()
JS数组遍历的几种方式 JS数组遍历,基本就是for,forin,foreach,forof,map等等一些方法,以下介绍几种本文分析用到的数组遍历方式以及进行性能分析对比 第一种:普通for循环 代 ...
- ormlite
id 主键 默认为false generatedId 自增长的主键 默认值是false generatedIdSequence 字符串名称的序列号 类同generatedId,但您可以指定序列的名称使 ...
- 常见iOS面试题 之 怎么判断一个类是否遵循某个协议
答案: 使用方法conformsToProtocol. 调用例子: BOOL isConform = [Student conformsToProtocol:@protocol(UIScrollVie ...
- 【转载】TCP粘包问题分析和解决(全)
TCP通信粘包问题分析和解决(全) 在socket网络程序中,TCP和UDP分别是面向连接和非面向连接的.因此TCP的socket编程,收发两端(客户端和服务器端)都要有成对的socket,因此,发送 ...
- POJ 2184 Cow Exhibition (01背包变形)(或者搜索)
Cow Exhibition Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 10342 Accepted: 4048 D ...
- Java 兔子问题(斐波那契数列)扩展篇
Java兔子问题(斐波那契数列)扩展篇 斐波那契数列指的是这样一个数列 0, 1, 1, 2,3, 5, 8, 13, 21, 34, 55, 89, 144, ...对于这个数列仅仅能说将兔子生产周 ...
- CAShapeLayer的使用
CAShapeLayer的使用 1.CAShapeLayer 简介 1.CAShapeLayer继承至CALayer,可以使用CALayer的所有属性值 2.CAShapeLayer需要与贝塞尔曲线配 ...
- Java中数组复制的几种方式以及数组合并
1.Object.clone() 简单直接,只能对源数组完整地复制 2.Arrays.copyOf(T[] original, int newLength) 可以只复制源数组中部分元素,但复制的起始位 ...
- isMemberOf与isKindOf的区别
这两个方法常常会困惑我们,它们有什么区别呢? 定义 首先,我们来看看它们的定义. isKindOfClass: 官方解释:Returns a Boolean value that indicates ...