restful——认证组件

认证组件简介:

只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件

认证功能局部使用:

1、写一个类,继承BaseAuthentication

 2、在视图类中使用:(不要加括号)

 

3、局部配置

4、认证功能的全局配置

  -在settings.py中配置

5、全局使用的局部禁用:

6、不存数据库的token验证

from rest_framework.exceptions import NotAuthenticated
from rest_framework.views import APIView
from  rest_framework.response import Response
from app01 import models
from app01.MySer import BookSerializer
import uuid

def get_token():
    return uuid.uuid4()

class AuthLogin(BaseAuthentication):
    def authenticate(self,request):
        token=request.GET.get('token')
        ret=models.UserToken.objects.filter(token=token).first()
        if ret:
            #说明这个人登录了
            return ret.user,token
            # return None
        else:
            # 说明没有登录
            raise NotAuthenticated('您没有登录')

class Login(APIView):
    authentication_classes = []
    def post(self, request):
        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:
            # user.user_type拿到的是数字
            print(user.user_type)
            # 我想拿中文get_字段名_display()
            print(user.get_user_type_display())


            # 校验通过
            response['msg'] = '登录成功'
            # 随机字符串可以是用户名+当前时间生成md5值,
            # uuid4()  sdgfasfgasdg
            token = get_token()
            # 有问题! 所以我需要先查一下,如果有记录,更新token,如果没有,需要新增
            # models.UserToken.objects.create(token=token,user=user)
            # user = user 查询条件     defaults={'token':token} 更新
            models.UserToken.objects.update_or_create(user=user, defaults={'token': token})
            response['token'] = token
        else:
            response['status'] = 101
            response['msg'] = '用户名或密码错误'
        return Response(response)
View Code

PS:

-BaseAuthentication(规范了接口,模拟其它语言接口的概念)
        -def authenticate(self, request):
            raise NotImplementedError(".authenticate() must be overridden.")
        如果写了一个类,继承BaseAuthentication,但是没有重写authenticate,就会抛异常

choice的用法

# 0 是超级用户,1是普通用户,2 是2b用户
user_choice=((0,'超级用户'),(1,'普通用户'),(2,'2b用户'))
user_type = models.IntegerField(default=0,choices=user_choice)
# 我想拿中文get_字段名_display():
    print(user.get_user_type_display())

views.py中:

        user = models.User.objects.filter(name=name, password=pwd).first()
        if user:
            # user.user_type拿到的是数字
            print(user.user_type)
            # 我想拿中文get_字段名_display()
            print(user.get_user_type_display())

models.py中

class User(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    # 0 是超级用户,1是普通用户,2 是2b用户
    user_choice=((0,'超级用户'),(1,'普通用户'),(2,'2b用户'))
    user_type = models.IntegerField(default=0,choices=user_choice)
    # user_type = models.ForeignKey(to='Type',to_field='type_id')

 

drf内置了一些认证类 (了解):

-TokenAuthentication

-SessionAuthentication

 

posted @ 2019-02-22 20:53  萤huo虫  阅读(156)  评论(0编辑  收藏  举报