APIView源码解析
1、首先安装pip install djangorestframework
2、导入from rest_framework.views import APIView
class Courses(APIView):
def get(self, request):
course_list = Course.objects.all()
ret = []
for course in course_list:
ret.append({
"title": course.title,
"desc": course.desc
})
return HttpResponse(json.dumps(ret, ensure_ascii=False)) def post(self, request):
print(request.data)
return HttpResponse("ok")
3、url的设计:
url(r'^courses/', views.Courses.as_view()),
4、首先进入的是Courses类里边的APIView,点进去执行as_view()方法。源码如下:
def as_view(cls, **initkwargs):
"""
Store the original class on the view function. This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
"""
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)
view.cls = cls
view.initkwargs = initkwargs # Note: session based authentication is explicitly CSRF validated,
# all other authentication is CSRF exempt.
return csrf_exempt(view)
然后执行的是父类里边的as_view方法,返回的就是父类里边的view方法。
简单来说就是:
# url(r'^courses/', APIView.as_view()),
# url(r'^courses/', View.view),
5、用户一旦访问,开始执行:
执行父类的view,
view(reqeust):
self = cls(**initkwargs)
return self.dispatch(request, *args, **kwargs) # APIView.dispatch()
def dispatch(request, *args, **kwargs):
然后执行的就是dispatch,在我们的类里边找dispatch,找不到往APIView里边找,源码是:
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate? try:
self.initial(request, *args, **kwargs) # Get the appropriate handler method
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 response = handler(request, *args, **kwargs) except Exception as exc:
response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
简单来说:
def dispatch(request, *args, **kwargs):
# 1 重装一个新的request对象
# 2 认证组件,权限组件,频率组件
handler = getattr(self, request.method.lower())
response = handler(request, *args, **kwargs)
return response
APIView源码解析的更多相关文章
- DRF之APIView源码解析
目录 Django项目中的代码如下 APIView源码解析 源码解析总结 Django项目中的代码如下 urls.py中: from django.conf.urls import url from ...
- CBV源码与APIView源码解析
一.CBV源码解析 在我们写cbv的时候在url中和fbv的区别就是是否调用了as_view()方法,所以关键入手点就是这个方法 @classonlymethod # 这是类的绑定方法,这个cls是我 ...
- Django APIView源码解析
APIView使用:luffy项目中关于APIView的使用 在Django之 CBV和FBV中,我们是分析的from django.views import View下的执行流程,以下是代码 fro ...
- Django生命周期 URL ----> CBV 源码解析-------------- 及rest_framework APIView 源码流程解析
一.一个请求来到Django 的生命周期 FBV 不讨论 CBV: 请求被代理转发到uwsgi: 开始Django的流程: 首先经过中间件process_request (session等) 然后 ...
- CBV源码分析+APIVIew源码分析
{drf,resful,apiview,序列化组件,视图组件,认证组件,权限组件,频率组件,解析器,分页器,响应器,URL控制器,版本控制} 一.CBV源码分析准备工作: 新建一个Django项目 写 ...
- Django rest framework框架——APIview源码分析
一.什么是rest REST其实是一种组织Web服务的架构,而并不是我们想象的那样是实现Web服务的一种新的技术,更没有要求一定要使用HTTP.其目标是为了创建具有良好扩展性的分布式系统. 可用一句话 ...
- DRF-解析器组件源码解析
解析器组件源码解析 解析器组件源码解析 1 执行request.data 开始找重装的request中的data方法 2 在dispatch找到重装的request def dispatch(self ...
- rest-framework源码解析和自定义组件----版本
版本 url中通过GET传参自定义的版本 12345678910111213141516171819202122 from django.http import HttpResponsefrom dj ...
- 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新
本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...
随机推荐
- ubuntu上make menuconfig出错
如果使用make menuconfig的方式配置内核,又碰巧系统没有安装ncurses库(ubuntu系统默认就没有安装此库),就会出现错误,错误信息大体上如下: *** Unable to find ...
- wps去广告
彻底解决WPS弹出热点广告.WPS购物图标的办法 方法一:(一定有效) https://www.cnblogs.com/ytaozhao/p/5654149.html 一直用WPS,但一直有一个问题迟 ...
- Object 转 json 工具类
/** * 把数据对象转换成json字符串 DTO对象形如:{"id" : idValue, "name" : nameValue, ...} * 数组对象形如 ...
- [js]arguments属性
类数组 具有length属性的对象称为类数组 观察他的顺序 为什么能转换 for(let i=0;i<arr.length;i++){ console.log(arr[i]); } https: ...
- [LeetCode] 74. Search a 2D Matrix_Medium tag: Binary Search
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- Java - Selenium 环境配置
1. 安装Java JDK - 文件自己下 2. 配置环境变量-重要! 我的电脑-属性-高级-环境变量 添加 CLASSPATH 值 .;%JAVA_HOME%\lib;%JAVA_HOME%\li ...
- [附POC]Apache Struts2最新(CVE-2017-5638,S02-45)POC
#! /usr/bin/env python # encoding:utf-8 import urllib2 import sys from poster.encode import multipar ...
- 工作流引擎--swamp
什么是工作流引擎(Workflow Engine ) 例如开发一个系统最关键的部分不是系统的界面,也不是和数据库之间的信息交换,而是如何根据业务逻辑开发出符合实际需要的程序逻辑并确保其稳定性.易维 ...
- MongoDB--关于数据库及选择MongoDB的原因
用户用数据库提供的接口将数据写入,数据会以标准的格式存储起来. 不同数据库的区别:存放数据的组织不同,同时提供不同种类的查询,用户按照自己的需求选择合适的数据库. 可以将地理位置存储在MongoDB中 ...
- 利用yum升级Centos6的gcc版本,使其支持C++11
下面的可以在centos6下工作,centos7下有问题.可能是因为centos下的scl我是拷贝的文件,没有完全验证centos6下肯定没问题. https://my.oschina.net/u/5 ...