Django   发布时间:2022-04-10  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Django rest_framework 认证源码流程大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

<div id="cnblogs_posT_Body" class="blogpost-body">
<h1 class="title">一、请求到来后,都要先执行dispatch方法
<p class="title">dispatch根据请求方式的不同触发get/post/put/delete等方法

注意,APIView中的dispatch方法有很多的功能

dispatch(self,request,*args,**==title">第一步:对request进行加工(添加数据) request = self.initialize_request(request,**request =request self.headers = self.default_response_headers
    <span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt;:
        </span><span style="color: #008000;"&gt;#</span><span class="secondtitle"&gt;第二步:</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;处理版权信息</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;认证</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;权限</span>
            <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;请求用户进行访问频率的限制</span>
        self.initial(request,**<span style="color: #000000;"&gt;kwargs)

        </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Get the appropriate handler method</span>
        <span style="color: #0000ff;"&gt;if</span> request.method.lower() <span style="color: #0000ff;"&gt;in</span><span style="color: #000000;"&gt; self.http_method_names:
            handler </span>=<span style="color: #000000;"&gt; getattr(self,request.method.lower(),self.http_method_not_allowed)
        </span><span style="color: #0000ff;"&gt;else</span><span style="color: #000000;"&gt;:
            handler </span>=<span style="color: #000000;"&gt; self.http_method_not_allowed

        </span><span style="color: #008000;"&gt;#</span><span class="secondtitle"&gt; 第三步、执行:get/post/put/delete函数</span>
        response = handler(request,**<span style="color: #000000;"&gt;kwargs)

    </span><span style="color: #0000ff;"&gt;except</span><span style="color: #000000;"&gt; Exception as exc:
        response </span>=<span style="color: #000000;"&gt; self.handle_exception(exC)

    </span><span class="secondtitle"&gt;#第四步、</span><span style="color: #008000;"&gt; 对返回结果再次进行加工</span>
    self.response = self.finalize_response(request,response,**<span style="color: #000000;"&gt;kwargs)
    </span><span style="color: #0000ff;"&gt;return</span> self.response</pre>

<h1 class="title">二、上面是大致步骤,下面我们来具体分析一下
<h2 class="secondtitle">1、对request进行加工(添加数据)

我们来看看request里面都添加了那些数据

a、首先request = self.initialize_request(request,**kwargs)点进去,会发现:在request里面多加了四个,如下

initialize_request(self,**request object. parser_context =ntext(request)
    </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; request(
        request,parsers</span>=self.get_parsers(),<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;解析数据,默认的有三种方式,可点进去看</span>
        <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;self.get_authenticator优先找自己的,没有就找父类的</span>
        authenticators=self.get_authenticators(),<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;获取认证相关的所有类并实例化,传入request对象供request使用</span>
        negotiator=<span style="color: #000000;"&gt;self.get_content_negotiator(),parser_context</span>=<span style="color: #000000;"&gt;parser_context
    )</span></pre>

b、获取认证相关的类的具体 authenticators=self.get_authenticators(),

[auth() auth self.authentication_classes]

c、查看认证的类:self.authentication_classes

authentication_classes = api_setTings.DEFAULT_AUTHENTICATION_CLASSES

d、接着走进api_setTings

api_setTings = APISetTings(None,DEFAULTS,IMPORT_StriNGS) #点击继承的DEFAULTS类
DEFAULTS ={ .basicAuthentication

e、导入了类看看类里面具体干了什么

rest_framework.authentication rest_framework.authentication BaseAuthentication

f、看到里面有个authenticate方法和authenticate_header方法

ject):
<span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Authenticate the request and return a two-tuple of (user,token).
    </span><span style="color: #800000;"&gt;"""</span>
    <span style="color: #0000ff;"&gt;raise</span> NotImplementedError(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;.authenticate() must be overridden.</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)

</span><span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate_header(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Return a String to be used as the value of the `WWW-Authenticate`
    header in a `401 Unauthenticated` response,or `None` if the
    authentication scheR_426_11845@e should return `403 Permission Denied` responses.
    </span><span style="color: #800000;"&gt;"""</span>
    <span style="color: #0000ff;"&gt;pass</span></pre>

具体处理认证,从headers里面能获取用户名和密码

http Basic authentication against username/password. =
<span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate(self,request):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Returns a `User` if a correct username and password have been supplied
    using http Basic authentication.  Otherwise returns `None`.
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt;
    auth </span>=<span style="color: #000000;"&gt; get_authorization_header(request).split()

    </span><span style="color: #0000ff;"&gt;if</span> <span style="color: #0000ff;"&gt;not</span> auth <span style="color: #0000ff;"&gt;or</span> auth[0].lower() != b<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;basic</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;:
        </span><span style="color: #0000ff;"&gt;return</span> None   <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;返回none不处理。让下一个处理</span>

    <span style="color: #0000ff;"&gt;if</span> len(auth) == 1<span style="color: #000000;"&gt;:
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. No credentials provided.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)
    </span><span style="color: #0000ff;"&gt;elif</span> len(auth) > 2<span style="color: #000000;"&gt;:
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. Credentials String should not contain spaces.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)

    </span><span style="color: #0000ff;"&gt;try</span><span style="color: #000000;"&gt;:
        auth_parts </span>= base64.b64decode(auth[1]).decode(http_HEADER_ENCODING).partition(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;:</span><span style="color: #800000;"&gt;'</span>)   <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;用partition切割,保留了分割项冒号</span>
    <span style="color: #0000ff;"&gt;except</span><span style="color: #000000;"&gt; (TypeError,UnicodeDecodeError,binascii.Error):
        msg </span>= _(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid basic header. Credentials not correctly base64 encoded.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;raise</span><span style="color: #000000;"&gt; exceptions.AuthenticationFailed(msg)

    userid,password </span>= auth_parts[0],auth_parts[2]  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 返回用户和密码</span>
    <span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; self.authenticate_credentials(userid,password,request)

</span><span style="color: #0000ff;"&gt;def</span> authenticate_credentials(self,userid,request=<span style="color: #000000;"&gt;NonE):
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #800000;"&gt;
    Authenticate the userid and password against username and password
    with optional request for context.
    </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt;
    credentials </span>=<span style="color: #000000;"&gt; {
        get_user_R_426_11845@odel().USERNAME_FIELD: userid,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;password</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;: password
    }
    user </span>= authenticate(request=request,**<span style="color: #000000;"&gt;credentials)

    </span><span style="color: #0000ff;"&gt;if</span> user <span style="color: #0000ff;"&gt;is</span><span style="color: #000000;"&gt; None:
        </span><span style="color: #0000ff;"&gt;raise</span> exceptions.AuthenticationFailed(_(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Invalid username/password.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;))

    </span><span style="color: #0000ff;"&gt;if</span> <span style="color: #0000ff;"&gt;not</span><span style="color: #000000;"&gt; user.is_active:
        </span><span style="color: #0000ff;"&gt;raise</span> exceptions.AuthenticationFailed(_(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;User inactive or deleted.</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;))

    </span><span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt; (user,NonE)

</span><span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; authenticate_header(self,request):
    </span><span style="color: #0000ff;"&gt;return</span> <span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Basic realm="%s"</span><span style="color: #800000;"&gt;'</span> % self.www_authenticate_realm</pre>

g、当然restfulframework默认定义了两个类。我们也可以自定制类,自己有就用自己的了,自己没有就去找父类的了,但是里面必须实现authenticate方法,不然会报错。

title">2、进行以下操作(处理版权信息,认证,权限,访问频率限制)

    @H_675_156@处理版权信息 @H_675_156@认证 @H_675_156@权限 @H_675_156@请求用户进行访问频率的限制 @H_262_164@

    我们主要来看一下认证流程

    认证流程:

    a、首先self.initial(request,**kwargs)可以看到做了以下操作

    initial(self,**= self.get_format_suffix(** </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Perform content negotiation and store the accepted info on the request</span> neg =<span style="color: #000000;"&gt; self.perform_content_negotiation(request) request.accepted_renderer,request.accepted_media_type </span>=<span style="color: #000000;"&gt; neg </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Determine the API version,if versioning is in use.</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;2.1 处理版本信息</span> version,scheR_426_11845@e = self.determine_version(request,**<span style="color: #000000;"&gt;kwargs) request.version,request.versioning_scheR_426_11845@e </span>=<span style="color: #000000;"&gt; version,scheR_426_11845@e </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Ensure that the incoming request is permitted</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;2.2 认证</span>

    <span style="color: #000000;"> self.perform_authentication(request)
    <span style="color: #008000;">#<span style="color: #008000;"> 2.3 权限
    <span style="color: #000000;"> self.check_permissions(request)
    <span style="color: #008000;">#<span style="color: #008000;"> 2.4 请求用户进行访问频率的限制
    self.check_throttles(request)

    b、我们先来看认证,self.perform_authentication(request) 具体干了什么,按住ctrl点击进去

    request): 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.
        </span><span style="color: #800000;"&gt;"""</span><span style="color: #000000;"&gt;
        request.user   </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;执行request的user,这是的request已经是加工后的request了</span></pre>

    c、那么我们可以从视图里面导入一下request,找到request对象的user方法

    rest_framework.views request

    Django rest_framework 认证源码流程

    request,as authenticated by the authentication classes provided to the request. hasattr(self, self._user

    d、执行self._authenticate() 开始用户认证,如果验证成功后返回元组: (用户,用户Token)

    request using each authentication instance in turn. authenticator user_auth_tuple =s.APIException: self._not_authenticated()
            <span style="color: #0000ff;"&gt;if</span> user_auth_tuple <span style="color: #0000ff;"&gt;is</span> <span style="color: #0000ff;"&gt;not</span><span style="color: #000000;"&gt; None:
                self._authenticator </span>=<span style="color: #000000;"&gt; authenticator
                self.user,self.auth </span>= user_auth_tuple  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;返回一个元组,user,和auth,赋给了self,</span>
                <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 只要实例化request,就会有一个request对象,就可以request.user,request.auth了</span>
                <span style="color: #0000ff;"&gt;return</span><span style="color: #000000;"&gt;
    
        self._not_authenticated()</span></pre>

    e、在user_auth_tuple = authenticator.authenticate(self) 进行验证,如果验证成功,执行类里的authenticatie方法

    f、如果用户没有认证成功:self._not_authenticated()

    Ting an unauthenticated request.
        Defaults are None,AnonymousUser &amp; None.
        </span><span style="color: #800000;"&gt;"""</span>
        <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;如果跳过了所有认证,默认用户和Token和使用配置文件进行设置</span>
        self._authenticator = None  <span style="color: #008000;"&gt;#


    <span style="color: #0000ff;">if<span style="color: #000000;"> api_setTingS.UNAUTHENTICATED_USER:
    self.user = api_setTingS.UNAUTHENTICATED_USER() <span style="color: #008000;">#<span style="color: #008000;"> 默认值为:匿名用户AnonymousUser
    <span style="color: #0000ff;">else<span style="color: #000000;">:
    self.user = None <span style="color: #008000;">#<span style="color: #008000;"> None 表示跳过该认证

        <span style="color: #0000ff;"&gt;if</span><span style="color: #000000;"&gt; api_setTingS.UNAUTHENTICATED_TOKEN:
            self.auth </span>= api_setTingS.UNAUTHENTICATED_TOKEN()  <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 默认值为:None</span>
        <span style="color: #0000ff;"&gt;else</span><span style="color: #000000;"&gt;:
            self.auth </span>=<span style="color: #000000;"&gt; None
    
    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; (user,token)</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; 表示验证通过并设置用户名和Token;</span>
    <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; AuthenticationFailed异常</span></pre>

    title">3、执行get/post/delete等方法

    title">4、对返回结果在进行加工

    三、完整过程

    现在我们主要去分析rest_framework内部对这个url的具体实现过程。

        @H_675_156@首先我们访问http://127.0.0.1:8000/user/ 根据urls.py中的配置,执行views.TestView.as_view()函数 @H_675_156@

        as_view方法是被定义在rest_framework/views.py里面的一个静态方法,所以可以通过类名直接调用。

        Django rest_framework 认证源码流程

        @H_675_156@

        父类的as_view方法是定义在django/views/generic/base.py里面的View类中的方法。在这个方法中最终会执行cls.dispatch,在第一步中我们知道cls是

        Django rest_framework 认证源码流程

        @H_675_156@

        dispatch是定义在TestView继承的父类APIView(rest_framework/views.py)里面的方法。在这个方法里面,首先通过request = self.initialize_request(request,**kwargs)这条语句重新封装了request对象

        Django rest_framework 认证源码流程

        @H_675_156@

        initialize_request是APIView类里面的一个方法,重新封装了request对象,增加了一些属性信息

        Django rest_framework 认证源码流程

        @H_675_156@

        认证信息。主要通过APIView类中的get_authenticators(rest_framework/views.py)方法获取,这个方法会返回一个所有认证对象的列表
        在全局定义的authentication_classes = api_setTings.DEFAULT_AUTHENTICATION_CLASSES

        Django rest_framework 认证源码流程

        @H_675_156@

        默认的认证配置信息是在rest_framework/setTings.py文件中定义的

        Django rest_framework 认证源码流程

        @H_675_156@

        在rest_framework/authentication.py中定义了几种认证类型,一般情况我们需要自定义认证类,也可以使用django-oauth-toolkit组件进行认证。

        Django rest_framework 认证源码流程

        @H_675_156@dispatch中的initialize_request方法执行完成之后,还有执行一个重要方法是self.initial(request,**kwargs),这个方法也是APIView类里的。在这个方法里面初始化
        被重新封装的request对象
        实现功能:
          @H_675_156@版本处理 @H_675_156@用户认证 @H_675_156@权限 @H_675_156@访问频率限制 @H_262_164@

          Django rest_framework 认证源码流程

          @H_675_156@

          执行APIView里面的perform_authentication方法,该方法返回request.user,则会调用request.request object="" at="" 0x10e80deb8="">里面的user方法。在user方法里面最终调用了request类里面的_authenticate方法

          Django rest_framework 认证源码流程


          Django rest_framework 认证源码流程

          @H_675_156@

          执行rest_framework.request.request类中的_authenticate方法,这个方法会遍历认证类,并根据认证结果给self.user,self.auth赋值。由于user,和auth都有property属性,
          所以给赋值的时候先在先执行setter方法

          Django rest_framework 认证源码流程


          Django rest_framework 认证源码流程

          @H_675_156@

          dispatch中的initial方法执行完之后,会继续判断request.method并执行R_426_11845@ethod相应的R_426_11845@ethod.

          Django rest_framework 认证源码流程

          @H_675_156@

          执行TestView中定义的get方法,返回数据

大佬总结

以上是大佬教程为你收集整理的Django rest_framework 认证源码流程全部内容,希望文章能够帮你解决Django rest_framework 认证源码流程所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: