Django DRF认证组件的流程是什么
Django DRF认证组件的流程是什么?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!
视图函数中加上认证功能,流程见下图
import hashlibimport timedef get_random(name): md = hashlib.md5() md.update(bytes(str(time.time()),encoding='utf-8')) md.update(bytes(name,encoding='utf-8')) return md.hexdigest()from rest_framework.views import APIViewclass Login(APIView): authentication_classes = [AuthLogin] def post(self, request, *args, **kwargs): response = {'status': 100, 'msg': None} name = request.data.get('name') pwd = request.data.get('pwd') user = models.User.objects.filter(name=name, password=pwd).first() if user: response['msg'] = '登陆成功' # 随机字符串可以是用户名加当前时间生成的mds token = get_random(name) # 如果有记录,就只需要更新,不需要重新插入 # models.UserToken.objects.create(token=token,user=user) # 查询 更新 # user_agent models.UserToken.objects.update_or_create(user=user, defaults={'token': token}) response['token'] = token else: response['status'] = 101 response['msg'] = '用户名或密码错误' return Response(response)
from rest_framework.permissions import BasePermissionfrom rest_framework.exceptions import NotAuthenticatedfrom app01 import models# BaseAuthenticationclass AuthLogin(BaseAuthentication): def authenticate(self, request): # 封装后的request token = request.GET.get('token') # print(token) ret = models.UserToken.objects.filter(token=token).first() if ret: return ret.user,token else: raise NotAuthenticated('您没有登陆')
在def initial(self, request, *args, **kwargs):函数中找到认证功能
流程总结:
dispatch 方法里self.initial里面有个认证组件self.perform_authentication(request)到了APIview 返回了request.user (封装后的Request)去request类里找user方法,被包装成了属性,里面执行了一个方法,self._authticate方法self._authticate方法里从自己的authenticators一个一个的取东西,authenticators于是查看authenticators,是初始化的时候init传过来了,self.authenticators = authenticators or()到dispatch里找初始化的时候,也就是APIView的initialize_request方法传了self.authenticators,里面是一个get_authenticators的方法self.authentication_classes 是[类1,类2,类3]一个一个取,加括号执行。生成一个一个对象.最后返回到前面的Request的_authenticate方法拿到对象之后,执行user_auth_tuple = authenticator.authenticate(self)注意authenticate是需要在视图函数中自己定义的,self.user, self.auth = user_auth_tuple返回两个值,流程结束。感谢各位的阅读!看完上述内容,你们对Django DRF认证组件的流程是什么大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。