Rest Framework第四天-认证组件、权限组件、频率组件

                                                          认证组件

一、认证简介

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

二、局部使用 

(1) models层:

class User(models.Model):
    username=models.CharField(max_length=32)
    password=models.CharField(max_length=32)
    user_type=models.IntegerField(choices=((1,'超级用户'),(2,'普通用户'),(3,'二笔用户')))

class UserToken(models.Model):
    user=models.OneToOneField(to='User')
    token=models.CharField(max_length=64)

(2)新建认证类(验证通过return两个参数)

from rest_framework.permissions import BasePermission
class MyPermission(BasePermission):
    message = '不是超级用户,查看不了'
    def has_permission(self,request,view):
        token=request.query_params.get('token')
        ret=models.UserToken.objects.filter(token=token).first()
        print(ret.user.get_type_display())
        if ret.user.type==1:
        # 超级用户可以访问

            return True
        else:
            return False

(3)view层

def get_random(name):
    import hashlib
    import time
    md=hashlib.md5()
    md.update(bytes(str(time.time()),encoding='utf-8'))
    md.update(bytes(name,encoding='utf-8'))
    return md.hexdigest()

from django.shortcuts import render,HttpResponse

# Create your views here.
import json
from rest_framework.views import APIView
from app01 import models
from utils.common import *
from rest_framework.response import Response


class Login(APIView):
    def post(self,request,*args,**kwargs):
        response=MyResponse()
        name=request.data.get('name')
        pwd=request.data.get('pwd')
        user=models.UserInfo.objects.filter(name=name,pwd=pwd).first()
        if user:
        #     生成一个随机字符串
            token=get_token(name)
            # 如果不存在,会创建,如果存在,会更新
            ret=models.UserToken.objects.update_or_create(user=user,defaults={'token':token})
            response.status=100
            response.msg='登录成功'
            response.token=token

        else:
            response.msg='用户名密码错误'

        return Response(response.get_dic())


# class Course(APIView):
#     authentication_classes=[MyAuth,]
#     def get(self,request):
#         token=request.query_params.get('token')
#         ret=models.UserToken.objects.filter(token=token).first()
#         if ret:
#
#             return HttpResponse(json.dumps({'name':'python'}))
#         return HttpResponse(json.dumps({'msg':'您没有登录'}))

class Course(APIView):
    authentication_classes=[MyAuth,]
    permission_classes=[MyPermission,]
    throttle_classes=[VisitThrottle,]
    def get(self,request):
        print(request.user)
        print(request.auth)

        return HttpResponse(json.dumps({'name':'python'}))

局部使用,需要在视图类里加入:

authentication_classes = [TokenAuth, ]

全局使用,需要在settings中加入:

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",]
}

认证类使用顺序:先用视图类中的验证类,再用settings里配置的验证类,最后用默认的验证类

                                                        权限组件

一、权限简介

只用超级用户才能访问指定的数据,普通用户不能访问,所以就要有权限组件对其限制

二、局部使用

from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
    message = '不是超级用户,查看不了'
    def has_permission(self, request, view):
        # user_type = request.user.get_user_type_display()
        # if user_type == '超级用户':
        user_type = request.user.user_type
        print(user_type)
        if user_type == 1:
            return True
        else:
            return False
class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')

局部使用只需要在视图类里加入:

permission_classes = [UserPermission,]

三、全局使用

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}

权限类使用顺序:先用视图类中的权限类,再用settings里配置的权限类,最后用默认的权限类

                                                           频率组件

一、简介

为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次

二、自定义频率类,自定义频率规则

自定义的逻辑

#(1)取出访问者ip
# (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
# (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
# (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
# (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败

代码:

class MyThrottles():
    VISIT_RECORD = {}
    def __init__(self):
        self.history=None
    def allow_request(self,request, view):
        #(1)取出访问者ip
        # print(request.META)
        ip=request.META.get('REMOTE_ADDR')
        import time
        ctime=time.time()
        # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问
        if ip not in self.VISIT_RECORD:
            self.VISIT_RECORD[ip]=[ctime,]
            return True
        self.history=self.VISIT_RECORD.get(ip)
        # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
        while self.history and ctime-self.history[-1]>60:
            self.history.pop()
        # (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
        # (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
        if len(self.history)<3:
            self.history.insert(0,ctime)
            return True
        else:
            return False
    def wait(self):
        import time
        ctime=time.time()
        return 60-(ctime-self.history[-1])

三、内置频率类及局部使用

from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle):
    scope = 'xxx'
    def get_cache_key(self, request, view):
        return self.get_ident(request)

在setting里配置:(一分钟访问三次)

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}

视图层的配置:

throttle_classes = [MyThrottles,]

错误信息提示的配置:

class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission, ]
    throttle_classes = [MyThrottles,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')
    def throttled(self, request, wait):
        from rest_framework.exceptions import Throttled
        class MyThrottled(Throttled):
            default_detail = '傻逼啊'
            extra_detail_singular = '还有 {wait} second.'
            extra_detail_plural = '出了 {wait} seconds.'
        raise MyThrottled(wait)

内置频率限制类:

BaseThrottle是所有类的基类:方法:def get_ident(self, request)获取标识,其实就是获取ip,自定义的需要继承它

AnonRateThrottle:未登录用户ip限制,需要配合auth模块用

SimpleRateThrottle:重写此方法,可以实现频率现在,不需要咱们手写上面自定义的逻辑

UserRateThrottle:登录用户频率限制,这个得配合auth模块来用

ScopedRateThrottle:应用在局部视图上的(忽略)

四、内置频率类及全局使用

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES':['app01.utils.VisitThrottle',],
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17513503/article/details/83280628