1.

    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进行加工,其实是实例化一个Requst并传入一个对象列表
''''''
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 #执行method方法并返回response
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

2.

    def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request) return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)

3.

    def get_authenticators(self):
"""
Instantiates and returns the list of authenticators that this view can use.
"""
return [auth() for auth in self.authentication_classes]

4.自定义类,可以重写authentication_classes

class HostView(APIView):
authentication_classes=[] def get(self,request,*args,**kwargs):
# 原来request对象,django.core.handlers.wsgi.WSGIRequest
# 现在的request对象,rest_framework.request.Request\
self.dispatch
print(request.user)
print(request.auth)
return Response('主机列表')

5.

    def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
#版本处理
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
#权限认证
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)

6.

    def perform_authentication(self, request):
"""
Perform authentication on the incoming request. Note that if you override this and simply 'pass', then authentication
will instead be performed lazily, the first time either
`request.user` or `request.auth` is accessed.
"""
request.user

7.执行Request类中的user属性

@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user

8.

    def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
#循环对象列表
for authenticator in self.authenticators:
try:
#返回一个元祖(self.force_user, self.force_token)
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return self._not_authenticated()

9.

class MyBasicAuthentication(BasicAuthentication):
def authenticate_credentials(self, userid, password, request=None):
if userid == 'alex' and password == '':
return ('alex','authaaaaaaaaaaaa')
raise APIException('认证失败')

rest framework 源码流程的更多相关文章

  1. Rest Framework源码流程解析

    目录: 一 整体流程 二 具体流程 一 请求进来之后,都要先执行dispatch方法,dispatch方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的d ...

  2. Django Rest Framework框架源码流程

    在详细说django-rest-framework源码流程之前,先要知道什么是RESTFUL.REST API . RESTFUL是所有Web应用都应该遵守的架构设计指导原则. REST是Repres ...

  3. Django rest framework源码分析(4)----版本

    版本 新建一个工程Myproject和一个app名为api (1)api/models.py from django.db import models class UserInfo(models.Mo ...

  4. Django rest framework源码分析(1)----认证

    目录 Django rest framework(1)----认证 Django rest framework(2)----权限 Django rest framework(3)----节流 Djan ...

  5. Django rest framework源码分析(2)----权限

    目录 Django rest framework(1)----认证 Django rest framework(2)----权限 Django rest framework(3)----节流 Djan ...

  6. Django rest framework 源码分析 (1)----认证

    一.基础 django 2.0官方文档 https://docs.djangoproject.com/en/2.0/ 安装 pip3 install djangorestframework 假如我们想 ...

  7. Django REST framework 源码剖析

    前言 Django REST framework is a powerful and flexible toolkit for building Web APIs. 本文由浅入深的引入Django R ...

  8. Django Rest Framework源码剖析(五)-----解析器

    一.简介 解析器顾名思义就是对请求体进行解析.为什么要有解析器?原因很简单,当后台和前端进行交互的时候数据类型不一定都是表单数据或者json,当然也有其他类型的数据格式,比如xml,所以需要解析这类数 ...

  9. Django Rest Framework源码剖析(二)-----权限

    一.简介 在上一篇博客中已经介绍了django rest framework 对于认证的源码流程,以及实现过程,当用户经过认证之后下一步就是涉及到权限的问题.比如订单的业务只能VIP才能查看,所以这时 ...

随机推荐

  1. C++ Primer 笔记——标准库类型string

    1.如果使用等号初始化一个变量,实际上执行的是拷贝初始化,编译器吧等号右侧的初始值拷贝到新创建的对象中去:如果不使用等号则执行的是直接初始化. std::string str = "Test ...

  2. dubbo支持哪些通信协议和序列化协议

    dubbo支持的通信协议 dubbo协议 dubbo://192.168.0.1:20188 默认就是走dubbo协议的,单一长连接,NIO异步通信,基于hessian作为序列化协议 适用的场景就是: ...

  3. 一脸懵逼学习Hive的元数据库Mysql方式安装配置

    1:要想学习Hive必须将Hadoop启动起来,因为Hive本身没有自己的数据管理功能,全是依赖外部系统,包括分析也是依赖MapReduce: 2:七个节点跑HA集群模式的: 第一步:必须先将Zook ...

  4. jQuery数字滚动(模拟网站人气、访问量递增)原创

    插件描述:实现数字上下滚动,模拟网站人气.访问量递增的动画效果,兼容性如下: 使用方法 $(el).runNum(val,params);   参数详解 val:数值型(默认70225800): pa ...

  5. centos 6 切换base源

    切换为阿里云源: mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup && wg ...

  6. JMeter通过自定义jar调用和BeanShell源码

    自定义jar包引用 原始java代码,代码的作用的是根据指定的字符串,生成执行长度的随机字符串 package com; import java.util.Random; public class r ...

  7. windows docker常用命令

    关键词 示例 作用 attach sudo docker run -itd ubuntu:14.04 /bin/bash 进入容器 exec docker exec -it mysql bash 在容 ...

  8. 2018牛客网暑假ACM多校训练赛(第十场)D Rikka with Prefix Sum 组合数学

    原文链接https://www.cnblogs.com/zhouzhendong/p/NowCoder-2018-Summer-Round10-D.html 题目传送门 - https://www.n ...

  9. 009 pandas的Series

    一:创建 1.通过Numpy数组创建 2.属性查看 3.一维数组创建(与numpy的创建一样) 4.通过字典创建 二:应用Numpy数组运算 1.获取值 numpy的数组运算,在Series中都被保留 ...

  10. 反射-Emit

    一.Emit Emit,可以称为发出或者产出.在Framework中,与Emit相关的类基本都存在与System.Reflection,Emit命名空间下.可见Emit是作为反射的一个元素存在,反射可 ...