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. Loadrunner11.0 录制手机App脚本的方法二

    lr11安装一个移动补丁以后,就可以支持抓包文件直接转换为http/html协议的脚本.下面简单说一下过程. 1.工作思路:手机连接可上外网wifi,在手机wifi中设置本机ip的网络地址,然后在本机 ...

  2. Ubuntu下创建桌面快捷方式(以Pycharm为例)

    之后要在Ubuntu虚拟机上玩PyTorch,安装了Pycharm. 然而每次打开Pycharm需要在其bin目录下进入终端,然后输入sh pycharm.sh,很麻烦.既然Ubuntu是桌面系统,为 ...

  3. Python入门:求1-2+3-4+5...99的所有数的和

    num =1 sum =0 while num <=99: if num % 2 ==1: sum = sum + num num =num +1 print(sum) 2.求1-2+3-4+5 ...

  4. 谷歌浏览器Software Reporter Tool长时间占用CPU解决办法

    什么是Software Reporter Tool Software Reporter Tool是一个Chrome清理工具,用于清理谷歌浏览器中不必要或恶意的扩展,应用程序,劫持开始页面等等.当你安装 ...

  5. Go语言之defer关键字

    类似于java中的finally, 在函数返回来执行, 它用来保证函数一定会作一些事情. package main import "fmt" func main() { defer ...

  6. combination sum(I, II, III, IV)

    II 简单dfs vector<vector<int>> combinationSum2(vector<int>& candidates, int targ ...

  7. 秒懂C#通过Emit动态生成代码

    首先需要声明一个程序集名称, 1 // specify a new assembly name 2 var assemblyName = new AssemblyName("Kitty&qu ...

  8. 异象石(就是sdio宝藏那题)

    题解: 之前这道题写过两次题解了吧.. 实现的时候可以用set<int,cmp>来实现按照dfn排序 代码: 感觉别人的分类讨论比我的简单.. 但我觉得我这个写起来也不烦就不看别人的了.. ...

  9. Tychonov Theorem

    (Remark: The proof presented in this post is a reorganization and interpretation of that given by Ja ...

  10. day8.python文件操作

    打开和关闭文件 open函数 用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写. file = open(file_name [, access_ ...