Restframework 频率throttle组件实例-3
频率逻辑:
from rest_framework.throttling import BaseThrottle import time VISIT_RECORD={} class VisitThrottle(BaseThrottle): def __int__(self): self.history =None def allow_request(self, request, view): """ 限制IP每分钟访问不能超过3次 :param request: :param view: :return: """ #确定访问IP remote_addr =request.META.get("REMOTE_ADDR") print(remote_addr) #获取当次访问时间 ctime =time.time() #if 第一次访问 if remote_addr not in VISIT_RECORD: VISIT_RECORD[remote_addr]= [ctime,] return True history =VISIT_RECORD.get(remote_addr) self.history =history while history and ctime -history[-1]> 60: history.pop() if len(history)<3: history.insert(0,ctime) return True else: return False def wait(self): #当前访问时间 ctime =time.time() #访问时间历史记录self.history return 60-(ctime- self.history[-1])
应用频率逻辑
class BookView(APIView): authentication_classes = [UserAuth] permission_classes = [SVIPPermission] throttle_classes = [VisitThrottle] def get(self,request): """ 查看所有书籍 :param request: :return: """ book_list=Book.objects.all() serializer= BookSerializer(book_list,many=True) return Response(serializer.data) def post(self,request): """ 添加一条书籍 :param request: :return: """ serializer=BookSerializer(data=request.data,many=True) if serializer.is_valid(): serializer.save()#create操作. return Response(serializer.data) else: return Response(serializer.errors) class BookViewDetail(APIView): def get(self,request,pk): edit_book =Book.objects.get(pk=pk) serializer =BookSerializer(edit_book,many=False) return Response(serializer.data) def put(self,request,pk): edit_book=Book.objects.get(pk=pk) serializer =BookSerializer(data=request.data,instance=edit_book) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) def delete(self,request,id): edit_obj =Book.objects.get(pk=id).delete() return Response("11")
全局应用逻辑
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES': (
'app01.utils.auth_class.UserAuth',
),
'DEFAULT_PERMISSION_CLASSES': (
'app01.utils.svippermission_class.SVIPPermission',
),
"DEFAULT_THROTTLE_CLASSES": (
"app01.utils.throttle_class.VisitThrottle",
),
}
频率设置的第二种方法:
视图逻辑
class VisitThrottle(SimpleRateThrottle): scope="visit_rate" def get_cache_key(self,request, view): return self.get_ident(request)
全局配置
REST_FRAMEWORK={ "DEFAULT_THROTTLE_RATES": { "visit_rate": "10/m", },