restful框架有哪些(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()创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!