Django DRF认证流程(解析源码)

一、安装restframework

pip install djangorestframework
pip install markdown       # 为browsable API 提供Markdown支持。
pip install django-filter  # Filtering支持。

二、定义路由

urlpatterns = [
    path('admin/', admin.site.urls),
    path('dog/', views.DogView.as_view())
]

三、定义视图函数

class DogView(APIView):
    def get(self, request, *arg, **kwarg):
        return Response('获取Dog')

    def post(self, request, *arg, **kwarg):
        return Response('创建Dog')

    def put(self, request, *arg, **kwarg):
        return Response('更新Dog')

    def delete(self, request, *arg, **kwarg):
        return Response('删除Dog')

源码剖析

①当restframework的CBV请求进来会先走dispatch方法,按Ctrl点击dispatch进入源码。

 #源码,通过反射找到get、post等函数进行执行。
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)

②对原始的request进行加工

request = self.initialize_request(request, *args, **kwargs)
self.request = request

此步骤进行对request的重新封装

按住Ctrl点击initialize_request查看加工详情

"""
当执行dispatch时候穿过去的self都是DogView的对象,
执行的方法都会先到DogView里面去找,没有的话在去父类找。
所以self.get_authenticators()先会去DogView里面找,如果没有在去父类找
"""
return Request(
      # 原来的request
      request,
      parsers=self.get_parsers(),
      # 认证
      authenticators=self.get_authenticators(),
      negotiator=self.get_content_negotiator(),
      parser_context=parser_context
  )

③进入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]

# self.authentication_classes源码
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

④进入Request查看对initialize_request进行的封装

"""
小知识: 在Pycharm中点击View->Tool Windows->Structure(快捷键Alt+F7)查看py文件下的所有方法
def __init__(self, request, parsers=None, authenticators=None,
          negotiator=None, parser_context=None):
 assert isinstance(request, HttpRequest), (
     'The `request` argument must be an instance of '
     '`django.http.HttpRequest`, not `{}.{}`.'
     .format(request.__class__.__module__, request.__class__.__name__)
 )

 self._request = request
 self.parsers = parsers or ()
 self.authenticators = authenticators or ()

由源码可知想要获取原生request使用request._request即可。
获取认证类的对象列表 request.authenticators

⑤进入dispatch下的initial

#def dispatch(self, request, *args, **kwargs):
try:
   self.initial(request, *args, **kwargs)

self.initial(request, *args, **kwargs)进行认证

# 该request是已经封装好的request
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)

在这里插入图片描述

self.perform_authentication(request)中得到request.user,所以去Request()中寻找user方法,得到调用了self._authenticate()
self.perform_authentication(request)实现认证

"""
for循环的是authentication_classes中的对象,然后执行该对象的authenticate方法
认证通过后返回一个元组,不通过抛出错误。
"""
def _authenticate(self):
   """
   Attempt to authenticate the request using each authentication instance
   in turn.
   """
   for authenticator in self.authenticators:
       try:
           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

四、自定义验证规则

from rest_framework.exceptions import AuthenticationFailed


class MyAuthentication(object):
  def authenticate(self, request):
       token = request._request.GET.get('token')
       if not token:
           raise AuthenticationFailed('用户认证失败')
       return ('xiaohao', 19)
   def authenticate_header(self, val):
       pass
# 在DogView中加入authentication_classes = [MyAuthentication,]

自定义验证类名, 重写源码中的authenticate使其找authenticator时在DogView找到authentication_classes

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值