framework —— auth认证+权限+限流==》 联合使用
1.业务需求
a. 对匿名用户进行限制,每个用户1分钟允许访问10次
b. 对匿名用户进行限制,每个用户1分钟允许访问5次,登录的用户1分钟访问10次,vip用户1分钟允许访问20次
2.目录结构
3.urls.py
4.app04/views.py:
from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.throttling import BaseThrottle,SimpleRateThrottle from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from app02 import models # Create your views here. #用户认证 class MyAuthentication(BaseAuthentication): """ All authentication classes should extend BaseAuthentication. """ def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ token = request.query_params.get('token') obj = models.Userinfo.objects.filter(token=token).first() if obj: return (obj.username,obj) return None def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass #用户权限控制 class MyPermission(object): message = "无权访问" def has_permission(self,request,view): if request.user: # print(request.user) return True return False #管理员权限控制 class AdminPermission(object): message = "无权访问" def has_permission(self,request,view): if request.user == 'zxc': return True return False #匿名用户 class AnonThrottle(SimpleRateThrottle): scope = 'zxc_anon' def get_cache_key(self, request, view): #返回None,就不限制 #登录用户不限制 if request.user: return None #匿名用户就需要限制了 return self.get_ident(request) #登录用户 class UserThrottle(SimpleRateThrottle): scope = 'zxc_user' def get_cache_key(self, request, view): #登录用户 if request.user: return request.user return None #展示列表,无需登录就可以访问 class IndexView(APIView): authentication_classes = [MyAuthentication,] permission_classes = [] throttle_classes = [AnonThrottle,UserThrottle] def get(self,request,*args,**kwargs): self.dispatch return Response('访问首页') #展示列表,必须登录之后才可以访问 class IndexView(APIView): authentication_classes = [MyAuthentication,] permission_classes = [MyPermission,] throttle_classes = [AnonThrottle,UserThrottle] def get(self,request,*args,**kwargs): self.dispatch return Response('访问首页')
5.settings.py:
6.用户数据
验证:
登录用户:
登录超过10次就无法访问,给限制了
匿名用户一样,登录5次之后就给限制了。管理员没加进来,原理一样。