限制
DRF内置了基本的限制类,首先我们自己动手写一个限制类,熟悉下限制组件的执行过程。
自定义限制类
import time visit_record = {} class MyThrottle(object): def __init__(self): self.history = None def allow_request(self, request, view): # 拿到当前的请求的ip作为访问记录的 key ip = request.META.get('REMOTE_ADDR') # 拿到当前请求的时间戳 now = time.time() if ip not in visit_record: visit_record[ip] = [] # 把当前请求的访问记录拿出来保存到一个变量中 history = visit_record[ip] self.history = history # 循环访问历史,把超过10秒钟的请求时间去掉 while history and now - history[-1] > 10: history.pop() # 此时 history中只保存了最近10秒钟的访问记录 if len(history) >= 3: return False else: # 判断之前有没有访问记录(第一次来) self.history.insert(0, now) return True def wait(self): """告诉客户端还需等待多久""" now = time.time() return self.history[-1] + 10 - now # history = ['9:56:12', '9:56:10', '9:56:09', '9:56:08'] # '9:56:18' - '9:56:12' # history = ['9:56:19', '9:56:18', '9:56:17', '9:56:08'] # 最后一项到期的时间就是下一次允许请求的时间 # 最后一项到期的时间:now - history[-1] > 10 # 最后一项还剩多少时间过期 # history[-1] + 10 - now
视图使用
from auth_demo.throttle import MyThrottle # 登录之后才能看到数据接口 class TestAuthView(APIView): throttle_classes = [MyThrottle, ]#视图局部使用 def get(self, request): return Response('这个视图里面的数据只有登录后才能看到!')
全局使用
# 在settings.py中设置rest framework相关配置项 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES": ["auth_demo.throttle.MyThrottle", ] }
使用内置限制类
from rest_framework.throttling import SimpleRateThrottle class VisitThrottle(SimpleRateThrottle): scope = "xxx" def get_cache_key(self, request, view): return self.get_ident(request)
全局配置
REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES": ["auth_demo.throttle.VisitThrottle", ], "DEFAULT_THROTTLE_RATES": { "xxx": "5/m", }}
局部配置
from auth_demo.throttle import VisitThrottle # 登录之后才能看到数据接口 class TestAuthView(APIView): throttle_classes = [VisitThrottle, ] def get(self, request): return Response('这个视图里面的数据只有登录后才能看到!')