Django的rest_framework认证组件之局部设置源码解析

Stella981
• 阅读 466

前言:

  Django的rest_framework组件的功能很强大,今天来我来给大家剖析一下认证组件

下面进入正文分析,我们从视图开始,一步一步来剖析认证组件

1、进入urls文件

url(r'^login/', views.LoginCBV.as_view(),name="login"),

2、然后执行LoginCBV这个类的as_view方法

3、LoginCBV这个类是我们自己的写的,但是LoginCBV类根本没有写as_view这个方法,那么我们该怎么办? 此时我们应该去找LoginCBV的父类,看父类是否as_view方法

4、先确认LoginCBV这个类的父类,很清楚,我们看到LoginCBV这个类的父类是APIView这个类

class LoginCBV(APIView):

5、下面我们去APIView这个类中查找是否有as_view这个方法,我们在APIView这个类中找到了as_view方法,这个被classmethod修饰符修饰,也就是说这个方法是一个类方法,由一个类本身就可以调用这个方法,这个时候大家在会议一下,在urls文件中,是不是一个类在调用as_view方法。

如果大家都classmethod这个修饰符不清楚,可以看下我的这篇博客:https://www.cnblogs.com/bainianminguo/p/10475204.html

@classmethod
    def as_view(cls, **initkwargs):

6、下面我们来具体看下as_view这个方法,到底做了什么事情?下面是方法的源码

@classmethod
    def as_view(cls, **initkwargs):
        """
        Store the original class on the view function.

        This allows us to discover information about the view when we do URL
        reverse lookups.  Used for breadcrumb generation.
        """
        if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
            def force_evaluation():
                raise RuntimeError(
                    'Do not evaluate the `.queryset` attribute directly, '
                    'as the result will be cached and reused between requests. '
                    'Use `.all()` or call `.get_queryset()` instead.'
                )
            cls.queryset._fetch_all = force_evaluation

        view = super(APIView, cls).as_view(**initkwargs)
        view.cls = cls
        view.initkwargs = initkwargs

        # Note: session based authentication is explicitly CSRF validated,
        # all other authentication is CSRF exempt.
        return csrf_exempt(view)

我们来重点看下需要我们知道的,首先这个函数的返回值是一个view方法

Django的rest_framework认证组件之局部设置源码解析

 接着我们看下view这个方法,从这里我们可以看到,view就是执行APIView父类的as_view方法,下面我们接着去找APIView类的父类的as_view方法

Django的rest_framework认证组件之局部设置源码解析

 7、进入APIView父类中,我们看到APIView类的父类是View

class APIView(View):

 8、进入View类中,看下as_view这个方法到底了干了什么?

@classonlymethod
    def as_view(cls, **initkwargs):
        """
        Main entry point for a request-response process.
        """
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (cls.__name__, key))

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            return self.dispatch(request, *args, **kwargs)
        view.view_class = cls
        view.view_initkwargs = initkwargs

        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view

下面我们来分析这个方法的源码,方法的返回值是view这个函数,而view这个函数的返回值是self.dispatch这个方法

Django的rest_framework认证组件之局部设置源码解析

 9、下面我们首先要找到self.dispatch这个方法,然后在看下这个方法到底干了什么?

 这个self到底是哪个类的实例呢?我们来梳理一下子类和父类的关系

LoginCBV【类】------->APIView【类】------->View【类】------>view【方法】-----》dispatch【方法】

那么我们就需要先从LoginCBV这个类中找dispatch方法,发现没有找到,然后继续找LoginCBV这个类的父类,也就是APIView这个类,看这个类是否dispatch方法

10、我们最终在APIView这个类中找到了dispatch方法,所以这里调的dispatch方法一定是APIView这个类的方法

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 = 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

            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

这个方法很重要,我们来看下

首先rest_framework处理后的request

Django的rest_framework认证组件之局部设置源码解析

 然后看下self.initialize.request方法干了什么,当然找这个方法到底在是哪个类的方法,也是要按照之前我们找dispatch方法的一样,我这里就直接找到这个方法了,self.initialize.request这个方法是APIView这个类的方法

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
        )

这个函数返回一个Request的实例对象,然后我们在看下Request这个类的,Request类的源码如下

class Request(object):
    """
    Wrapper allowing to enhance a standard `HttpRequest` instance.

    Kwargs:
        - request(HttpRequest). The original request instance.
        - parsers_classes(list/tuple). The parsers to use for parsing the
          request content.
        - authentication_classes(list/tuple). The authentications used to try
          authenticating the request's user.
    """

    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 ()
        self.negotiator = negotiator or self._default_negotiator()
        self.parser_context = parser_context
        self._data = Empty
        self._files = Empty
        self._full_data = Empty
        self._content_type = Empty
        self._stream = Empty

        if self.parser_context is None:
            self.parser_context = {}
        self.parser_context['request'] = self
        self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET

        force_user = getattr(request, '_force_auth_user', None)
        force_token = getattr(request, '_force_auth_token', None)
        if force_user is not None or force_token is not None:
            forced_auth = ForcedAuthentication(force_user, force_token)
            self.authenticators = (forced_auth,)

Django的rest_framework认证组件之局部设置源码解析

不知道大家是否明白这段代码的意思,如果authenticators为真,则self.authenticators等于authenticators,如果authenticators为假,则self.authenticators等于一个空的元组

self.authenticators = authenticators or ()

 我们这里要看下实例化Request这个类的时候,authenticators这个参数传递的是什么?

我们在回到initlize_request方法的返回值,下面我们要来看下self.get_authenticators()方法是在做什么

Django的rest_framework认证组件之局部设置源码解析

 下面看下self.get_authenticators()这个方法的源码,从字面的我们就可以理解,self.authentication_classes是一个认证的类的列表。auth()是每个类的实例对象,这个方法的返回值就是列表,列表中的元素就是每个认证类的实例对象,这里先剧透一下,authentication_class这个属性是由我们自己的配置的

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

 到这里,APIView类中的dispatch方法的initialize_request条线就做完了,就是给我们返回了一个新的Request类的实例,这个实例的authenticators就包括我们认证组件相关的类的实例对象

下面我们继续往下走APIView类的dispatch方法,走self.initial方法

Django的rest_framework认证组件之局部设置源码解析

 11、下面先看下initial方法的源码

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)

Django的rest_framework认证组件之局部设置源码解析

 12、我们这里来看下认证组件干了什么事情?进入认证组件perform_authentication方法。只返回一个request.user

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

13、莫名其妙,返回一个实例的属性?其实这里大家不要忘记了,如果一个类的方法被property修饰了,调用这个方法的就可以使用属性的方式调用,而不用加括号了,如果大家不清楚,可以看我这篇博客:https://www.cnblogs.com/bainianminguo/p/9950607.html

14、下面我们看下request.user到底是什么?我们先要知道request是什么?看下面的截图

在dispatch方法中initial方法的参数有一个request,而这个request就是initialize_request的返回值,而initialize_request的返回值就是Request的实例对象

Django的rest_framework认证组件之局部设置源码解析

Django的rest_framework认证组件之局部设置源码解析

 这个request有一个user的属性或者方法,我们下面来找下

15、下面我们来看下request.user到底是个什么东西?我们在Request类中确实找到了user这个方法,这个方法也被property装饰器装饰了,所以也印证了我们之前的猜测了,request.user是一个被property修饰的方法

@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

16、然后看下self._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

        self._not_authenticated()

Django的rest_framework认证组件之局部设置源码解析

如果符合规范,则返回None,如果不符合规范,则raise抛出错误

 到这里,我们就认证组件的源码梳理完了,下面我们来看下具体怎么写认证组件

 17、下面进入如何写认证组件

我们的类中要有这么一个属性。

Django的rest_framework认证组件之局部设置源码解析

然后认证组件的类中要

Django的rest_framework认证组件之局部设置源码解析

 18、做认证,我们是通过一个token来做的,每次用户登陆,我们都会给他重新一个token,然后把这个token告诉客户,下次客户来访问带着token,我们就认为认证通过了

所以我们先设计表,一个model表,一个Token表,两张表是一对一的关系

class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

class Token(models.Model):
    user = models.OneToOneField(to=User)
    token = models.CharField(max_length=128)

 19、然后我们写用户登陆的处理逻辑

from django.http import JsonResponse

class LoginCBV(APIView):
    def get(self,request):
        pass

    def post(self,request):
        name = request.data.get("name")
        pwd = request.data.get("pwd")

        obj = models.User.objects.filter(name=name,pwd=pwd).exists()
        res = {"code":200,"message":"","token":""}
        if obj:
            user_obj = models.User.objects.filter(name=name,pwd=pwd).first()
            token = create_token(name)
            models.Token.objects.update_or_create(user_obj,defaults={"token":token})

            token_obj = models.Token.objects.get(user=user_obj)
            res["token"] = token_obj.token

        else:
            res["code"] = 201
            res["message"] = "用户名或者密码错误"
        import json
        return JsonResponse(json.dumps(res))

Django的rest_framework认证组件之局部设置源码解析

上面的update_or_create的方法写错了,正确的写法是下面的写法

models.Token.objects.update_or_create(user=user_obj,defaults={"token":token})

20、这里还写了一个生成token的函数,加盐的盐为用户的名称

Django的rest_framework认证组件之局部设置源码解析

 利用时间和用户的名称计算出来一个md5值,作为这次登陆的token

import hashlib
import time
def create_token(user):
    now = time.time()
    test_md5 = hashlib.md5(bytes(str(now),encoding="utf-8"))
    test_md5.update(bytes(user,encoding="utf-8"))
    return test_md5.hexdigest()

 21、下面我们开始写的认证组件,如果我们想控制访问这条url:

url(r'^book_cbv/', views.Book_cbv.as_view(),name="test3"),

22、那么我们就需要进入Book_cbv这个类中来做操作,这个属性我们之前也看到了,名称必须是authentication,且值要为一个list

Django的rest_framework认证组件之局部设置源码解析

 23、最后我们下Book_auther这个类

class Book_auther(BaseAuthentication):
    def authenticate(self,request):
        token = request.GET.get("token")
        token_obj = models.Token.objects.filter(token=token).first()
        if token_obj:
            return token_obj.user.name,token_obj.token
        else:
            raise exceptions.AuthenticationFailed("验证失败")
    def authenticate_header(self,request):
        pass

Django的rest_framework认证组件之局部设置源码解析

 24、最后我们用postman测试一下,首先先用post登陆一下,生成一下token

Django的rest_framework认证组件之局部设置源码解析

然后看下Token表中是否有token字段

Django的rest_framework认证组件之局部设置源码解析

 25、我们再次用postman登录一下,看下token是否会更新,我们看到token已经更新

Django的rest_framework认证组件之局部设置源码解析

 26、我们首先先不携带token去访问book表,看下效果,提示验证失败

Django的rest_framework认证组件之局部设置源码解析

27、下面我们携带token去访问,这样就可以返回查询到的结果了

Django的rest_framework认证组件之局部设置源码解析

 大家要慢慢的体会

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这