RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
rest_framework认证源码分析

认证源码分析

位置 :

APIVIew----》dispatch方法---》self.initial(request, *args, **kwargs)---->有认证,权限,频率三个版块

在汉阳等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供网站设计制作、网站制作 网站设计制作定制开发,公司网站建设,企业网站建设,品牌网站设计,成都全网营销,成都外贸网站建设,汉阳网站建设费用合理。

分析:

只读认证源码: self.perform_authentication(request)---》
self.perform_authentication(request)就一句话:request.user,需要去drf的Request对象中找user属性(方法)---》
Request类中的user方法,刚开始来,没有_user,走 self._authenticate()

核心:Request类的 _authenticate(self):

1.在需要进行认证的视图类中添加(认证类是自己写的类,该类继承了BaseAuthentication):

2.此时apiview里的 authentication_classes就变成了自己第一步在视图函数类里定义的了,而不会去自己的配置文件里找

3.然后正常执行到apiview里的dispatch方法:

4.dispatch方法内部又调用了initialize_request方法,返回了一个新的request对象

5.authenticators这个的值是get_authenticators()方法的返回值:返回值是一个个自己定义的继承了BaseAuthentication类的认证类对象

6.Request类中的authenticators变成了自定义类的对象

7.在继续走apiview里的dispatch方法里的initial方法

8.进入认证模块的方法

9.进入新封装request对象里

10.核心_authenticate方法

def _authenticate(self):
    # self是Request对象,所以去Request对象里找authenticators,
    # 最后self.authenticators的结果就是一个列表,列表里面是一个个自定义认证类的对象
    for authenticator in self.authenticators:
        try:
            # 此时authenticator就是认证类的对象,对象调用了authenticate方法,这个方法是需要我们在认证类里重新写的
            # 这个方法有两个返回值
            user_auth_tuple = authenticator.authenticate(self)
        except exceptions.APIException:
            self._not_authenticated()
            raise

        if user_auth_tuple is not None:
            self._authenticator = authenticator
            # 这两个返回值给了Request对象,就是request.user和request.auth(这就是为什么要求自己重新写的authenticate方法要有两个返回值了)
            self.user, self.auth = user_auth_tuple
            return

    self._not_authenticated()

新闻标题:rest_framework认证源码分析
文章地址:http://scyingshan.cn/article/dsogdhe.html