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源码解析的更多相关文章

  1. DRF之APIView源码解析

    目录 Django项目中的代码如下 APIView源码解析 源码解析总结 Django项目中的代码如下 urls.py中: from django.conf.urls import url from ...

  2. CBV源码与APIView源码解析

    一.CBV源码解析 在我们写cbv的时候在url中和fbv的区别就是是否调用了as_view()方法,所以关键入手点就是这个方法 @classonlymethod # 这是类的绑定方法,这个cls是我 ...

  3. Django APIView源码解析

    APIView使用:luffy项目中关于APIView的使用 在Django之 CBV和FBV中,我们是分析的from django.views import View下的执行流程,以下是代码 fro ...

  4. Django生命周期 URL ----> CBV 源码解析-------------- 及rest_framework APIView 源码流程解析

    一.一个请求来到Django 的生命周期   FBV 不讨论 CBV: 请求被代理转发到uwsgi: 开始Django的流程: 首先经过中间件process_request (session等) 然后 ...

  5. CBV源码分析+APIVIew源码分析

    {drf,resful,apiview,序列化组件,视图组件,认证组件,权限组件,频率组件,解析器,分页器,响应器,URL控制器,版本控制} 一.CBV源码分析准备工作: 新建一个Django项目 写 ...

  6. Django rest framework框架——APIview源码分析

    一.什么是rest REST其实是一种组织Web服务的架构,而并不是我们想象的那样是实现Web服务的一种新的技术,更没有要求一定要使用HTTP.其目标是为了创建具有良好扩展性的分布式系统. 可用一句话 ...

  7. DRF-解析器组件源码解析

    解析器组件源码解析 解析器组件源码解析 1 执行request.data 开始找重装的request中的data方法 2 在dispatch找到重装的request def dispatch(self ...

  8. rest-framework源码解析和自定义组件----版本

    版本 url中通过GET传参自定义的版本 12345678910111213141516171819202122 from django.http import HttpResponsefrom dj ...

  9. 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新

    本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...

随机推荐

  1. 【Python爬虫】Requests库的基本使用

    Requests库的基本使用 阅读目录 基本的GET请求 带参数的GET请求 解析Json 获取二进制数据 添加headers 基本的POST请求 response属性 文件上传 获取cookie 会 ...

  2. 机器Coding For WinForm

    declare @objname varchar(90)='AutoProjectModel'declare @modelns varchar(90)='ACL.Models'declare @dpc ...

  3. 在同一台电脑上部署多个tomcat服务器

    因为在写一些小的项目的时候,需要另外用到一台图片服务器,所以不得不开启多个tomcat了. 在这里我用的是tomcat 9.0,一个是正常时的tomcat,一个是图片服务器,在这里我就用tomcat1 ...

  4. python练习题-day4

    1.写代码,有如下列表,按照要求实现每一个功能 li = ["alex", "WuSir", "ritian", "barry&q ...

  5. bat、sh等批处理文件(脚本文件)

    批处理文件(batch file):也被称为批处理程序或脚本,可以简化日常或重复性任务.本质是无格式的文本文件,它包含一条或多条命令.(1).bat是dos下的批处理文件,在window系统上执行的文 ...

  6. EscapeDataString URI 字符串太长

    /// <summary> /// 处理 无效的 URI: URI 字符串太长.问题 /// </summary> /// <param name="value ...

  7. PHPstorm破解方法及xdebug的断点调试

    原文地址:http://www.php.cn/php-weizijiaocheng-381903.html 相信用PHPstorm的程序员肯定很多,令人头疼的是下载的PHPstorm是有使用期限的,小 ...

  8. 一、程序设计与C语言

    @程序:用特殊的编程语言编写的代码,用于表达如何解决问题. @编程语言的作用:编程语言不是用来和计算机交谈的,而是用它来描述要求计算机如何解决问的过程或方法.计算机只能执行(懂得)机器语言. @辗转相 ...

  9. dfs模版

    dfs #include <stdio.h> #include <string.h> char Map[16][16]; int mv[16][16]; //mv[i][j] ...

  10. 阿里云香港主机自动换IP

    为什么要写这个脚本原因你懂的,现在都是直接封IP pip3 install aliyun-python-sdk-alidns aliyun-python-sdk-domain aliyun-pytho ...