Python rest-framework 中类的继承关系(as_view)
一. 背景
最近几天一直在学习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)的更多相关文章
- 在Entity Framework 中实现继承关系映射到数据库表
继承关系映射到数据库表中有多种方式: 第一种:TPH(table-per-hiaerachy) 每一层次一张表 (只有一张表) 仅使用名为父类的类型名的一张表,它包含了各个子类的所有属性信息,使用区分 ...
- PHP中类的继承关系
在PHP中,我时常会写一个类,类写了一个共用方法,然后让子类去继承就能得到相应的功能.假设大致有这么一个父类: 1 <?php 2 class Father{ 3 4 public functi ...
- selenium之python源码解读-webdriver继承关系
一.webdriver继承关系 在selenium中,无论是常用的Firefox Driver 还是Chrome Driver和Ie Drive,他们都继承至selenium\webdriver\re ...
- UI基础:UI中类的继承关系图,最基本的视图分析
首先,UI中常用的UIwindow.UILabel.UIButton.UITextField属于UIView的子类.UITextField和UILabel和UIwindow自身没有初始化方法,需要使用 ...
- PythonI/O进阶学习笔记_4.自定义序列类(序列基类继承关系/可切片对象/推导式)
前言: 本文代码基于python3 Content: 1.python中的序列类分类 2. python序列中abc基类继承关系 3. 由list的extend等方法来看序列类的一些特定方法 4. l ...
- 第7.6节 Python中类的继承机制详述
在本章第一节,介绍了面向对象程序设计的三个特征:封装.继承和多态,前面章节重点介绍了封装和多态,由于Python语言是多态语言,对象的类型不再由继承等方式决定,而由实际运行时所表现出的具体行为来决定, ...
- Entity Framework Code First 映射继承关系
转载 http://www.th7.cn/Program/net/201301/122153.shtml Code First如何处理类之间的继承关系.Entity Framework Code Fi ...
- python中类的继承
python中类的继承 在python中面向对象编程中实现继承,以下面一个实例进行说明. class SchoolMenber(): # __init__类似于c++中的构造函数 # __init__ ...
- (转)Python异常类的继承关系
原文:https://blog.csdn.net/Dragonfli_Lee/article/details/52350793 https://www.cnblogs.com/Lival/p/6203 ...
随机推荐
- Kafka文件存储机制
一.topic中partition存储分布 在本地的kafka中,我们只启动一个broker,创建两个topic:single-todo和single-todo-vip ,每个topic有两个part ...
- 跨域请求之jsonp的实现方式
ajax请求受同源策略影响,不允许进行跨域请求,而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的js代码,在sr ...
- js 从基础入门 到放弃 001
快速入门 JavaScript代码可以直接嵌在网页的任何地方,不过通常我们都把JavaScript代码放到<head>中: <html> <head> <s ...
- java验证身份证合理性
package com.tiantian.util; import java.util.Calendar;import java.util.HashMap;import java.util.Map;i ...
- 怎样使用Navicat Premium导出导入mysql数据库
首先,在Navicat Premium中连接要导出数据库的mysql数据库. 2 1.填写好连接数据库的信息后就可以连接到需要导出的数据库了. 3 打开要导出的数据库. 4 将数据库的结构和数据导出为 ...
- ubuntu14.04 安装五笔输入法(fcitx)
ubuntu 14.04安装完成之后,一打字,默认的ibus一直在显示.解决办法,直接卸载ibus,使用fcitx. fictix拼音有fcitx-pinyin.fcitx-sogoupinyin.f ...
- JS: 数组扁平化
数组扁平化 什么是数组扁平化? 数组扁平化就是将一个多层嵌套的数组 (Arrary) 转化为只有一层. // 多层嵌套 [1, 2, [3, 4]] // 一层 [1, 2, 3, 4] 递归实现 思 ...
- MySQL多源复制(八)
一.什么是多源复制 MySQL 5.7发布后,在复制方面有了很大的改进和提升.比如开始支持多源复制(multi-source)以及真正的支持多线程复制了.多源复制可以使用基于二进制日志的复制或者基于事 ...
- POJ 1118
#include<iostream> #include<set> #include<stdio.h> #include<math.h> #include ...
- Java之集合(十一)IdentityHashMap
转载请注明源出处:http://www.cnblogs.com/lighten/p/7381905.html 1.前言 查看JDK源码总是能发现一些新东西,IdentityHashMap也是Map的一 ...