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. linux下的抓包

    1. 查看网卡名字 cat /proc/net/dev 2.抓取外网进来的包 tcpdump -i eth0 port -s -w .pcap 3.抓取自己服务器上的两个程序之间访问的数据 换成 lo ...

  2. shiro 单点登录原理 实例

    原创 2017年02月08日 17:39:55 4006 Shiro 1.2开始提供了Jasig CAS单点登录的支持,单点登录主要用于多系统集成,即在多个系统中,用户只需要到一个中央服务器登录一次即 ...

  3. 关于如何在Listener中注入service和ServletContextListener源码分析

      今天在做项目时突然发现我该如何向listener中注入service对象,因为监听器无法使用注解注入. 此时有人会想用以下代码通过xml的方式注入: ApplicationContext cont ...

  4. 使用heptiolabs/eventrouter收集K8S的事件

    k8s的heapster项目中止以后, 事件收集的项目,就推荐使用https://github.com/heptiolabs/eventrouter项目了. 部署文档很简单,但有两个问题要解决: 一, ...

  5. 一脸懵逼学习MapReduce的原理和编程(Map局部处理,Reduce汇总)和MapReduce几种运行方式

    1:MapReduce的概述: (1):MapReduce是一种分布式计算模型,由Google提出,主要用于搜索领域,解决海量数据的计算问题. (2):MapReduce由两个阶段组成:Map和Red ...

  6. vue.js学习:1.0到2.0的变化(区别)

    一.生命周期 1.1.0的生命周期: 周期 解释 init 组件刚刚被创建,但Data.method等属性还没被计算出来 created 组件创建已经完成,但DOM还没被生成出来 beforeComp ...

  7. HTML5语音输入方法

    谷歌的网站是时逛时新啊,今天在他们首页发现了HTML5的新玩法——语音搜索.可惜的是只有webkit核心的浏览器才能使用.用法很简单只需要在input添加属性 x-webkit-speech 即可,例 ...

  8. MVC区域area

    1.当项目业务比较庞大,可以通过区域来分拆. 2.添加区域时,默认会生成一下文件. 3.Application_Start()必需含有AreaRegistration.RegisterAllAreas ...

  9. 标准I/O的缓冲

    标准I/O实现了三种类型的用户缓冲,并为开发者提供了接口,可以控制缓冲区类型和大小. 无缓冲(Unbuffered) 不执行用户缓冲.数据直接提交给内核.因为这种无缓冲模式不支持用户缓冲(用户缓冲一般 ...

  10. Asp.Net Mvc 返回类型总结

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...