rest_framework框架实现之(认证)

一认证

我们可以想想,我们要访问一个页面,需不需要对其进行认证,希望进入页面的时候看到哪些内容,一般是根据用户的不同而不同

首先,我们先设计一个表,如何知道对方通过了验证,我们可以考虑给其加一个token,并且每个人都有不同的权限(大小)

#models.py
from django.db import models

class UserInfo(models.Model):
    user_type_choices=(
        (1,'普通用户'),
        (2,'VIP'),
        (3,"SVIP")
    )
    user_type=models.IntegerField(choices=user_type_choices)
    username=models.CharField(max_length=32,unique=True)
    password=models.CharField(max_length=32)

class UserToken(models.Model):
    user=models.OneToOneField(to='UserInfo') #默认就是UserInfo表的id
    token=models.CharField(max_length=64)

其次,需要设计token,token一般是一长串字符串,我们可以使用md5对其进行转化

#views.py
def
md5(user): import hashlib,time ctime=str(time.time()) m=hashlib.md5(bytes(user,encoding='utf-8')) #使用bytes方法直接让str变成bytes m.update(bytes(ctime,encoding='utf-8')) return m.hexdigest()

 设计验证方法

#views.py
from rest_framework.views import exceptions
from api import models
from rest_framework.authentication import BaseAuthentication
#BaseAuthentication类强制要求重写 authenticate函数,要不然抛出异常 .authenticate() must be overridden

class
Auth_yanzheng(BaseAuthentication): def authenticate(self, request): token = request._request.GET.get('token') token_obj = models.UserToken.objects.filter(token=token).first() if not token_obj: raise exceptions.AuthenticationFailed('用户认证失败') # 在rest framework内部将两个字段赋值给request,以供后续操作使用 return (token_obj.user, token_obj) #返回元组 def authenticate_header(self, request): #这个要写要不然报错 pass

token从哪里获得?当然是用户登录的时候

class AuthView(APIView): #根据用户登录,找出token,有就更新,没有就新建
    authentication_classes = [Auth_yanzheng]
def post(self,request,*args,**kwargs):
        ret={'code':1000,'msg':None}
        try:
            user=request._request.POST.get('username')
            pwd=request._request.POST.get('password')
            obj=models.UserInfo.objects.filter(username=user,password=pwd).first()

            if not obj:
                ret['code']=1001
                ret['msg']='用户名或密码错误'
            token=md5(user)
            models.UserToken.objects.update_or_create(user=obj,defaults={'token':token}) #注意update_or_create方法
            ret['token']=token
        except Exception as e:
            print(e)
            ret['code']=1002
            ret['msg']='请求异常'

        return JsonResponse(ret)

猜你喜欢

转载自www.cnblogs.com/mmyy-blog/p/11028768.html