def get_random_str(user): import hashlib,time ctime=str(time.time()) md5=hashlib.md5(bytes(user,encoding="utf8")) md5.update(bytes(ctime,encoding="utf8")) return md5.hexdigest() class Login2(APIView): # def get(self, request): # return render(request, 'login2.html') def post(self, request): res = {'code':1000,'msg':None} try: user = request.data.get('user') pwd = request.data.get('pwd') user_obj = User.objects.filter(user=user,pwd=pwd).first() print(user,pwd,user_obj) if not user_obj: res['code'] = 1001 res['msg'] = '用户名或密码错误' else: token = get_random_str(user) UserToken.objects.update_or_create(user=user_obj, defaults={"token": token}) res['token'] = token except Exception as e: res['code'] = 1002 res['msg'] = str(e) return JsonResponse(res, json_dumps_params={"ensure_ascii": False})
上面的认证系统是根据源码自己写的逻辑
下面我们就先来看看源码
from app01.models import UserToken from rest_framework.exceptions import AuthenticationFailed from rest_framework.authentication import BaseAuthentication class TokeAuth(BaseAuthentication): def authenticate(self, request): token = request.GET.get("token", None) print(token) token_obj = UserToken.objects.filter(token=token).first() if token_obj: return token_obj.user.user,token_obj else: raise AuthenticationFailed('认证失败!')
以上就是rest_framework提供的 认证