Django后端项目----restful framework 认证源码流程
一、请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法
注意,APIView中的dispatch方法有很多的功能
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 = argsself.kwargs = kwargs第一步:对request进行加工(添加数据)request = self.initialize_request(request, *args, **kwargs)self.request = requestself.headers = self.default_response_headers # deprecate?try:#第二步:#处理版权信息#认证#权限#请求用户进行访问频率的限制self.initial(request, *args, **kwargs)# Get the appropriate handler methodif 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# 第三步、执行:get/post/put/delete函数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
二、上面是大致步骤,下面我们来具体分析一下,看每个步骤中都具体干了什么事
1、对request进行加工(添加数据)
我们来看看request里面都添加了那些数据
a、首先 request = self.initialize_request(request, *args, **kwargs)点进去,会发现:在Request里面多加了四个,如下
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(), #解析数据,默认的有三种方式,可点进去看#self.get_authenticator优先找自己的,没有就找父类的authenticators=self.get_authenticators(), #获取认证相关的所有类并实例化,传入request对象供Request使用negotiator=self.get_content_negotiator(),parser_context=parser_context)
b、获取认证相关的类的具体 authenticators=self.get_authenticators(),
def get_authenticators(self):"""Instantiates and returns the list of authenticators that this view can use."""#返回的是对象列表return [auth() for auth in self.authentication_classes] #[SessionAuthentication,BaseAuthentication]
c、查看认证的类:self.authentication_classes
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES #默认的,如果自己有会优先执行直接的
d、接着走进api_settings
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) #点击继承的DEFAULTS类
DEFAULTS = {# Base API policies'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication', #这时候就找到了他默认认证的类了,可以导入看看'rest_framework.authentication.BasicAuthentication'),
e、导入了类看看类里面具体干了什么
from rest_framework.authentication import SessionAuthentication from rest_framework.authentication import BaseAuthentication
f、看到里面有个authenticate方法和authenticate_header方法
class BaseAuthentication(object):"""All authentication classes should extend BaseAuthentication."""def authenticate(self, request):"""Authenticate the request and return a two-tuple of (user, token)."""raise NotImplementedError(".authenticate() must be overridden.")def authenticate_header(self, request):"""Return a string to be used as the value of the `WWW-Authenticate`header in a `401 Unauthenticated` response, or `None` if theauthentication scheme should return `403 Permission Denied` responses."""pass
具体处理认证,从headers里面能获取用户名和密码
class BasicAuthentication(BaseAuthentication):"""HTTP Basic authentication against username/password."""www_authenticate_realm = 'api'def authenticate(self, request):"""Returns a `User` if a correct username and password have been suppliedusing HTTP Basic authentication. Otherwise returns `None`."""auth = get_authorization_header(request).split()if not auth or auth[0].lower() != b'basic':return None #返回none不处理。让下一个处理if len(auth) == 1:msg = _('Invalid basic header. No credentials provided.')raise exceptions.AuthenticationFailed(msg)elif len(auth) > 2:msg = _('Invalid basic header. Credentials string should not contain spaces.')raise exceptions.AuthenticationFailed(msg)try:auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') #用partition切割冒号也包括except (TypeError, UnicodeDecodeError, binascii.Error):msg = _('Invalid basic header. Credentials not correctly base64 encoded.')raise exceptions.AuthenticationFailed(msg)userid, password = auth_parts[0], auth_parts[2] # 返回用户和密码return self.authenticate_credentials(userid, password, request)def authenticate_credentials(self, userid, password, request=None):"""Authenticate the userid and password against username and passwordwith optional request for context."""credentials = {get_user_model().USERNAME_FIELD: userid,'password': password}user = authenticate(request=request, **credentials)if user is None:raise exceptions.AuthenticationFailed(_('Invalid username/password.'))if not user.is_active:raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))return (user, None)def authenticate_header(self, request):return 'Basic realm="%s"' % self.www_authenticate_realm
g、当然restfulframework默认定义了两个类。我们也可以自定制类,自己有就用自己的了,自己没有就去找父类的了,但是里面必须实现authenticate方法,不然会报错。
2、进行一下操作
- 处理版权信息
- 认证
- 权限
- 请求用户进行访问频率的限制
我们主要来看一下认证流程
认证流程:
a、首先 self.initial(request, *args, **kwargs)可以看到做了以下操作
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 requestneg = self.perform_content_negotiation(request)request.accepted_renderer, request.accepted_media_type = neg# Determine the API version, if versioning is in use.#2.1 处理版本信息version, scheme = self.determine_version(request, *args, **kwargs)request.version, request.versioning_scheme = version, scheme# Ensure that the incoming request is permitted#2.2 认证self.perform_authentication(request)# 2.3 权限self.check_permissions(request)# 2.4 请求用户进行访问频率的限制self.check_throttles(request)
b、我们先来看认证,self.perform_authentication(request) 具体干了什么,按住ctrl点击进去
def perform_authentication(self, request):"""Perform authentication on the incoming request.Note that if you override this and simply 'pass', then authenticationwill instead be performed lazily, the first time either`request.user` or `request.auth` is accessed."""request.user #执行request的user,这是的request已经是加工后的request了
c、那么我们可以从视图里面导入一下Request,找到request对象的user方法
from rest_framework.views import Request
@propertydef user(self):"""Returns the user associated with the current request, as authenticatedby the authentication classes provided to the request."""if not hasattr(self, '_user'):with wrap_attributeerrors():self._authenticate() #return self._user #返回user
d、执行self._authenticate() 开始用户认证,如果验证成功后返回元组: (用户,用户Token)
def _authenticate(self):"""Attempt to authenticate the request using each authentication instancein turn."""#循环对象列表for authenticator in self.authenticators:try:#执行每一个对象的authenticate 方法user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException:self._not_authenticated()raiseif user_auth_tuple is not None:self._authenticator = authenticatorself.user, self.auth = user_auth_tuple #返回一个元组,user,和auth,赋给了self,# 只要实例化Request,就会有一个request对象,就可以request.user,request.auth了returnself._not_authenticated()
e、在user_auth_tuple = authenticator.authenticate(self) 进行验证,如果验证成功,执行类里的authenticatie方法
f、如果用户没有认证成功:self._not_authenticated()
def _not_authenticated(self):"""Set authenticator, user & authtoken representing an unauthenticated request.Defaults are None, AnonymousUser & None."""#如果跳过了所有认证,默认用户和Token和使用配置文件进行设置self._authenticator = None #if api_settings.UNAUTHENTICATED_USER:self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户AnonymousUserelse:self.user = None # None 表示跳过该认证if api_settings.UNAUTHENTICATED_TOKEN:self.auth = api_settings.UNAUTHENTICATED_TOKEN() # 默认值为:Noneelse:self.auth = None# (user, token)# 表示验证通过并设置用户名和Token;# AuthenticationFailed异常
3、执行get/post/delete等方法
4、对返回结果在进行加工
转载于:https://www.cnblogs.com/TheLand/p/9070273.html
Django后端项目----restful framework 认证源码流程相关推荐
- Django rest_framework 认证源码流程
一.请求到来后,都要先执行dispatch方法 dispatch根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 def d ...
- REST framework 用户认证源码
REST 用户认证源码 在Django中,从URL调度器中过来的HTTPRequest会传递给disatch(),使用REST后也一样 # REST的dispatch def dispatch(sel ...
- 计算机毕业设计Python+django 宠物领养中心小程序(源码+系统+mysql数据库+Lw文档)
项目介绍 据世界动物保护协会统计,全世界大概有5亿只流浪狗和散养的狗和大致同样数量的流浪猫,而这些主要源于主人的弃养.同时,在很多地区,狗和猫都处于散养状态,这部分的动物,也经常会变成流浪动物.猫和狗 ...
- 计算机毕业设计Python+django的零食销售商城网站(源码+系统+mysql数据库+Lw文档)
项目介绍 随着人们生活条件的改善,人们对生活的追求也越来越高.在闲暇之时品尝上美味的零食,是当前很多人的一个休闲方式.当前临时市场鱼目混杂,种类繁多很多消费者不知道如何去选购更加美味可口的零食.尤其 ...
- 白鹭引擎egert+PHP后端手游宠物小精灵题材源码
白鹭引擎egert+PHP后端手游宠物小精灵题材源码下载 安卓+IOS+H5三端同步完整源码,MYSQL数据库,内含完整策划文档,卡牌类型的竖版游戏源码.前端是type script代码 后端是 PH ...
- Android安卓成品项目 购物商城系统源码apk
Android安卓成品项目 购物商城系统源码apk 安卓源码,成品项目,单机不联网项目,包含项目报告 登录注册,展示和修改个人信息,全部商家列表,讨论功能,添加购物车,联系,付款,查看订单记录,账户充 ...
- Gavin老师Transformer直播课感悟 - 通过Rasa Interactive对Rasa对话机器人项目实战之ConcertBot源码、流程及对话过程解密(四十三)
本文继续围绕工业级业务对话平台和框架Rasa,通过Rasa Interactive对Rasa对话机器人项目实战之ConcertBot源码.流程及对话过程进行解析. 一.通过Rasa Interacti ...
- PHP单页面加密视频教程附源码,thinkphp3.2最新版本项目实战视频教程(含源码)
php教程 当前位置:主页 > php教程 > thinkphp3.2最新版本项目实战视频教程(含源码) thinkphp3.2最新版本项目实战视频教程(含源码) 教程大小:2.1GB ...
- python人工智能项目实例-python人工智能项目实战,PDF+源码
原标题:python人工智能项目实战,PDF+源码 <python人工智能项目 Intelligent Projects Using Python> 实施机器学习和深度学习方法,使用Pyt ...
最新文章
- 用IE重起计算机或者关机
- 【电路原理】学习笔记(1):电路模型的基本变量
- 开源短地址_如何在短短5分钟内完成您的第一个开源贡献
- python 键盘输入_跟我一起学python | 探究07
- chmod递归授权文件夹(用法)
- python 解析pb文件_利用Python解析json文件
- 黑岩集团创建者Larry Fink 超长访谈
- 如何使用node批量修改文件后缀名
- 华中科技大学计算机学院本科生宿舍,[业余派]告诉你一个真正的华中科技大学...
- python 类调用不存在的方法_找不到Python方法,但在类中定义
- vue 监听输入法方法(js)
- Win10系统修改用户名以及C盘下Users用户名实操手册(实测有效)
- MySQL 性能优化:8 种常见 SQL 错误用法!
- 第十章 宠物商店 数据库建立插入信息
- 了解你的windows目录和系统文件(转)
- 淘宝直播2020年GMV4000亿,直播电商第一梯队出位还是出局?
- xilinx基础篇Ⅰ(3)ISE14.7下载FPGA
- MySQL基本使用(内容较多建议熟读并背诵)
- 国内电子数据取证鉴定标准最新合集(2020版)
- matlab 箱图 保存,[转载]Matlab图保存方法
热门文章
- 架构师必备!java三大特性用代码表现
- java打印unicode_java程序实现Unicode码和中文互相转换
- vbscript html 在线,在HTML中使用VBScript可用三种方法
- php fastdfs扩展,php如何安装fastdfs扩展
- set和map去重调用什么方法_Es6中Map对象和Set对象的介绍及应用
- 执行环境,作用域链,闭包
- 1688.比赛中的配对次数-LeetCode
- 攻击需要成本吗_石子厂成本大概多少?开一个石子厂都需要哪些设备,价格高吗 ?...
- sed shell 替换空格_shell三剑客之sed!
- Python字符串常用方法(split,partition,maketrans,strip...)