一 自定义频率类,自定义频率规则
自定义的逻辑
#(1)取出访问者ip # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走 # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间, # (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过 # (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
代码实现
import time class MyThrottles(): visitor_dic= {} def __init__(self): self.history=None def allow_request(self,request, view): #(1)取出访问者ip # print(request.META) ip=request.META.get(‘REMOTE_ADDR‘) ctime=time.time() # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问 if ip not in self.visitor_dic: self.visitor_dic[ip]=[ctime,] return True history = self.visitor_dic[ip] self.history=history # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间, while history and ctime-history[-1]>60: history.pop() # (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过 # (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败 if len(history)<3: history.insert(0,ctime) return True else: return False def wait(self): ctime=time.time() return 60-(ctime-self.history[-1]) views:
class Test(APIView): throttle_classes = [MyThrottle, ] def get(self, request): return HttpResponse(‘ok‘)
二 内置频率类
#内置的访问频率控制类SimpleRateThrottle #写一个类, 继承SimpleRateThrottle from rest_framework.throttling import BaseThrottle,SimpleRateThrottle class MyThrottle(SimpleRateThrottle): scope = ‘aaa‘ def get_cache_key(self, request, view): # 返回ip地址,两种方法: # ip=request.META.get(‘REMOTE_ADDR‘) # return ip return self.get_ident(request) #在setting中: REST_FRAMEWORK = { ‘DEFAULT_THROTTLE_RATES‘: { ‘aaa‘: ‘10/m‘ } } #局部使用,在视图类中写 throttle_classes = [MyThrottle, ] #全局使用,在setting中写 REST_FRAMEWORK = { ‘DEFAULT_THROTTLE_CLASSES‘: [‘app01.MyAuth.MyThrottle‘, ], } #局部禁用,在视图类中写 throttle_classes = []
from django.shortcuts import render, HttpResponse # Create your views here. from rest_framework.views import APIView from rest_framework import exceptions from app01.MyAuth import MyThrottle from rest_framework.request import Request from django.core.handlers.wsgi import WSGIRequest from rest_framework.parsers import JSONParser,FormParser class Test(APIView): # throttle_classes = [MyThrottle,] # parser_classes = [FormParser,] def get(self, request): print(type(request._request)) return HttpResponse(‘ok‘) def post(self,request): print(request.data) return HttpResponse(‘post‘) #等待时间显示中文信息 def throttled(self, request, wait): class MyThrottled(exceptions.Throttled): default_detail = ‘傻子‘ extra_detail_singular = ‘还剩 {wait} 秒才可以访问.‘ extra_detail_plural = ‘还剩 {wait} 秒才可以访问‘ raise MyThrottled(wait)
原文地址:https://www.cnblogs.com/liweiwei0307/p/10121738.html
时间: 2024-10-04 05:01:41