django 类通用视图详解
view() :
该类为所有类视图的父类,处于最底层,仅仅只对请求参数做校验后,给特定请求方法做特定调用。
用法:
url中定位到类方法:Aa.as_view() ——> View.as_view()方法对请求参数做判断后,转到View.dispatch() ——> 找到Aa.get() 或者Aa.post() 或者Aa.其他请求方法 ———>处理完成后返回view()
需要对请求方式做特定处理,可以自行修改dispatch()方法。
源码:
class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
该视图为所有类视图的父类,处于最底层,仅仅只实现了给特定的请求方式
进行特定方法的调度
"""
# http 所有请求方式的列表
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.
# 构造函数接收键值对参数,该参数来源于 URLconf配置中的传递
"""
# 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):
"""
# as_view 是一个闭包,做了一些校验工作后,再返回view函数
Main entry point for a request-response process.
"""
for key in initkwargs:
#as_view()方法中,如果传递的关键字参数key为默认的http 请求方法,则报错,
#默认不允许使用http请求方法作为参数
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__))
# as_view()方法中,如果传递过来的参数key 不在as_view()的属性中,也报错
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))
# view 方法作用是给请求对象添加三个参数,调用dispatch方法处理请求
def view(request, *args, **kwargs): # 作用:增加属性,调用dispatch方法
self = cls(**initkwargs) # 调用as_view 父类,创建一个实例对象
# 如果对象中有get属性,或者没有head属性,就创建head属性
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
# 为对象创建request、args和kwargs 三个属性
self.request = request
self.args = args
self.kwargs = kwargs
#调用dispatch 函数找到指定的请求方法,
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.
# 找到请求的方法,如果请求方法不在允许的列表中或者请求方法不存在就按照错误处理
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
# 如果请求方法存在,则取出该方法
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
# 如果不存在则报405错误
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())
def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb.
"""
response = http.HttpResponse()
response['Allow'] = ', '.join(self._allowed_methods())
response['Content-Length'] = '0'
return response
def _allowed_methods(self):
return [m.upper() for m in self.http_method_names if hasattr(self, m)]
用法实例:
class LoginUserView(View):
def dispatch(self, request, *args, **kwargs):
print "进入了改写后的dispatch方法"
discontext = super(LoginUserView, self).dispatch(request, *args, **kwargs)
print "没有改变调用请求方式,直接返回原始dispatch调用"
return discontext
def post(self, request):
context = userservice.login_user(request=request)
return JsonResponse(context)

ListView() :
django 类通用视图详解的更多相关文章
- ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解
原文 ASP.NET MVC 5 学习教程:Edit方法和Edit视图详解 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 ...
- 【译】ASP.NET MVC 5 教程 - 7:Edit方法和Edit视图详解
原文:[译]ASP.NET MVC 5 教程 - 7:Edit方法和Edit视图详解 在本节中,我们继续研究生成的Edit方法和视图.但在研究之前,我们先将 release date 弄得好看一点.打 ...
- 【转】UML类图与类的关系详解
UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类的关系有泛化(Generalization).实现(Realization).依赖(D ...
- String类的构造方法详解
package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...
- [转]c++类的构造函数详解
c++构造函数的知识在各种c++教材上已有介绍,不过初学者往往不太注意观察和总结其中各种构造函数的特点和用法,故在此我根据自己的c++编程经验总结了一下c++中各种构造函数的特点,并附上例子,希望对初 ...
- Scala 深入浅出实战经典 第63讲:Scala中隐式类代码实战详解
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- UML类图与类的关系详解
摘自:http://www.uml.org.cn/oobject/201104212.asp UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类 ...
- phpcms加载系统类与加载应用类之区别详解
<?php 1. 加载系统类方法load_sys_class($classname, $path = ''", $initialize = 1)系统类文件所在的文件路径:/phpcms ...
- c++类的构造函数详解
c++类的构造函数详解 一. 构造函数是干什么的 class Counter{ public: // 类Counter的构造函数 // 特点:以类名作为函数名,无返回类 ...
随机推荐
- Java压缩字符串的方法收集
说明: 1.一般来说要实现压缩,那么返回方式一般是用byte[]数组. 2.研究发现byte[]数组在转成可读的String时,大小会还原回原来的. 3.如果采用压缩之后不可读的String时,互相转 ...
- nginx+php简单配置环境
首先我的需求是: 1. 需要有PHP的服务.web目录存放在各处. 2. 需要有多个端口. 步骤: 1. 安装nginx php,我的系统是mac 所以安装使用brew, 一键完成... 2. 开启p ...
- HTTP Basic 验证客户端 C#实现笔记
HTTP Basic 验证客户端的原理:把HTTP头重的ContentType设置为:application/x-www-form-urlencoded如果HTTP头没有Authorization,那 ...
- css活用,半星星的效果
1.首先下载要用到星星字体 http://www.w3cplus.com/w3cplusDemo/demos/webFontIcon.html 2.css .cleanfloat::after{dis ...
- D3.js系列——布局:饼状图和力导向图
一.饼状图 在布局的应用中,最简单的就是饼状图. 1.数据 有如下数据,需要可视化: , , , , ]; 这样的值是不能直接绘图的.例如绘制饼状图的一个部分,需要知道一段弧的起始角度和终止角度,这些 ...
- 深入NIO Socket实现机制(转)
http://www.jianshu.com/p/0d497fe5484a# 前言 Java NIO 由以下几个核心部分组成: Buffer Channel Selector 以前基于net包进行so ...
- ajax 底层源码解析
对象: XMLHttpRequest 属性:readyState请求状态,开始请求时值为0直到请求完成这个值增长到4 responseText目前为止接收到的响应体,readyState<3此属 ...
- cocos2d-x 重力感应 加速器的使用
CSDN开通已有两三年,今天作为一名刚入行的菜鸟写下自己的第一篇Blog. 刚好项目中须要用到重力感应,google下发现重力感应的使用很easy. 例如以下: 第一步: 在当前层开启重力感应.函数: ...
- iOS定位服务CoreLocation
欢迎訪问我的新博客: 开发人员说 基于LBS的应用开发是当今移动开发中的一大热门, 当中主要涉及到地图和定位两个方面. iOS开发中, 定位服务依赖于CoreLocation框架, CLLocatio ...
- 转:[windows]DOS批处理添加任务计划
自动创建每周运行一次的计划任务 创建计划任务可用at,schtasks命令,schtasks提供了很多参数 命令schtasks SCHTASKS /Create [/S system [/U use ...