一. 背景

最近几天一直在学习restful framework的源代码,用户请求的流程,在路由系统这块遇到一个疑问,关于类的继承关系,当请求进来到路由这块,执行as_view()方法的时候,为什么会运行父类View的as_view()方法再执行到APIView的dispatch方法呢?这里记录一下一遍后面方便自己查阅

二. 代码示例

1. 路由

from django.conf.urls import url
from api import views as api_view urlpatterns = [
url(r'^index/', api_view.IndexView.as_view()),
]

2.  视图类

from rest_framework.response import  Response
from rest_framework.views import APIView class IndexView(APIView):
def get(self,request):
return Response('...')

三. 源代码分析

a. APIView的as_view方法

class APIView(View):

    @classmethod
def as_view(cls, **initkwargs): if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
def force_evaluation():
raise RuntimeError(
'Do not evaluate the `.queryset` attribute directly, '
'as the result will be cached and reused between requests. '
'Use `.all()` or call `.get_queryset()` instead.'
)
cls.queryset._fetch_all = force_evaluation view = super(APIView, cls).as_view(**initkwargs)
# 这里是继承了父类的方法as_view() view.cls = cls
view.initkwargs = initkwargs return csrf_exempt(view)

# 代码太多只截取部分代码

b. super(APIView,cls).as_view(**initkwargs)执行了什么操作

# super(APIView,self) 首先找到 APIView的父类(就是类 View),然后把View类的as_view属性 转换为类 APIView的属性
# 相当于将View中的as_view()中的代码复制到API_View中的as_view中

所以最终运行 super(APIView,cls).as_view(**initkwargs)执行了View中的as_view方法

class View(object):

    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):

        for key, value in six.iteritems(kwargs):
setattr(self, key, value) @classonlymethod
def as_view(cls, **initkwargs): 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)
# 运行这里吧最后执行了self.dispatch
view.view_class = cls
view.view_initkwargs = initkwargs update_wrapper(view, cls, updated=()) update_wrapper(view, cls.dispatch, assigned=())
return view # 返回了view函数

Python rest-framework 中类的继承关系(as_view)的更多相关文章

  1. 在Entity Framework 中实现继承关系映射到数据库表

    继承关系映射到数据库表中有多种方式: 第一种:TPH(table-per-hiaerachy) 每一层次一张表 (只有一张表) 仅使用名为父类的类型名的一张表,它包含了各个子类的所有属性信息,使用区分 ...

  2. PHP中类的继承关系

    在PHP中,我时常会写一个类,类写了一个共用方法,然后让子类去继承就能得到相应的功能.假设大致有这么一个父类: 1 <?php 2 class Father{ 3 4 public functi ...

  3. selenium之python源码解读-webdriver继承关系

    一.webdriver继承关系 在selenium中,无论是常用的Firefox Driver 还是Chrome Driver和Ie Drive,他们都继承至selenium\webdriver\re ...

  4. UI基础:UI中类的继承关系图,最基本的视图分析

    首先,UI中常用的UIwindow.UILabel.UIButton.UITextField属于UIView的子类.UITextField和UILabel和UIwindow自身没有初始化方法,需要使用 ...

  5. PythonI/O进阶学习笔记_4.自定义序列类(序列基类继承关系/可切片对象/推导式)

    前言: 本文代码基于python3 Content: 1.python中的序列类分类 2. python序列中abc基类继承关系 3. 由list的extend等方法来看序列类的一些特定方法 4. l ...

  6. 第7.6节 Python中类的继承机制详述

    在本章第一节,介绍了面向对象程序设计的三个特征:封装.继承和多态,前面章节重点介绍了封装和多态,由于Python语言是多态语言,对象的类型不再由继承等方式决定,而由实际运行时所表现出的具体行为来决定, ...

  7. Entity Framework Code First 映射继承关系

    转载 http://www.th7.cn/Program/net/201301/122153.shtml Code First如何处理类之间的继承关系.Entity Framework Code Fi ...

  8. python中类的继承

    python中类的继承 在python中面向对象编程中实现继承,以下面一个实例进行说明. class SchoolMenber(): # __init__类似于c++中的构造函数 # __init__ ...

  9. (转)Python异常类的继承关系

    原文:https://blog.csdn.net/Dragonfli_Lee/article/details/52350793 https://www.cnblogs.com/Lival/p/6203 ...

随机推荐

  1. Ceres入门笔记

    介绍 Ceres可以解决下列形式的边界约束鲁棒非线性最小二乘问题 (1) $\min\limits_{x}\quad \frac{1}{2} \sum\limits_{i}\rho_{i}\left( ...

  2. 三,memcached服务的两种访问方式

    memcached有两种访问方式,分别是使用telnet访问和使用php访问. 1,使用telnet访问memcacehd 在命令提示行输入, (1)连接memcached指令:telnet 127. ...

  3. webpack快速入门——实战技巧:webpack优化黑技能

    1.抽离jquery,vue(多个第三方类库抽离) 修改入口文件(webpack.config.js中) entry: { entry: './src/entry.js', jquery:'jquer ...

  4. [bug] JS sort 函数在 ios 中无效

    首先,请原谅我做一次标题党: 但我觉得从发现问题到最后解决问题的过程还是蛮有意思的,特此记录一下: 背景 近两天开发的航班延误宝是内嵌在客户端(android.ios)webview 中的 H5 页面 ...

  5. Xcode 10 如何创建自定义 Snippet

     或者 

  6. 简单HOG+SVM mnist手写数字分类

    使用工具 :VS2013 + OpenCV 3.1 数据集:minst 训练数据:60000张 测试数据:10000张 输出模型:HOG_SVM_DATA.xml 数据准备 train-images- ...

  7. (转)mysql explain详解

    原文:http://www.cnblogs.com/xuanzhi201111/p/4175635.html http://yutonger.com/18.html http://www.jiansh ...

  8. CSSREM

    一个CSS的px值转rem值的Sublime Text 3自动完成插件. 安装 下载本项目,比如:git clone https://github.com/flashlizi/cssrem 进入pac ...

  9. 使用fiddler抓手机包遇到问题

    1,http://blog.csdn.net/roland_sun/article/details/30078353 2,参照上面不周,不能实现用自己ip:8888端口下载出证书 解决办法,先从fid ...

  10. Android4.0 Launcher 源码分析2——Launcher内容加载绑定详细过程

    Launcher在应用启动的时候,需要加载AppWidget,shortcut等内容项,通过调用LauncherModel.startLoader(),开始加载的工作.launcherModel中加载 ...