from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
from rest_framework import exceptions
RECORD = {
}
class MyThrottle(BaseThrottle):
def allow_request(self,request,view):
"""
# 返回False,限制
# 返回True,通行
:param request:
:param view:
:return:
"""
"""
a. 对匿名用户进行限制:每个用户1分钟允许访问10次
- 获取用户IP request 112.122.221.122
"""
import time
ctime = time.time()
ip = self.get_ident()
if ip not in RECORD:
RECORD[ip] = [ctime,]
else:
# [4507862389234,3507862389234,2507862389234,1507862389234,]
time_list = RECORD[ip]
while True:
val = time_list[-1]
if (ctime-60) > val:
time_list.pop()
else:
break
if len(time_list) > 10:
return False
time_list.insert(0,ctime)
return True
def wait(self):
import time
ctime = time.time()
first_in_time = RECORD[self.get_ident()][-1]
wt = 60 - (ctime - first_in_time)
return wt
class MySimpleRateThrottle(SimpleRateThrottle):
scope = "zClass"
def get_cache_key(self, request, view):
return self.get_ident(request)
class LimitView(APIView):
authentication_classes = []
permission_classes = []
throttle_classes=[MySimpleRateThrottle,]
def get(self,request,*args,**kwargs):
self.dispatch
return Response('控制访问频率示例')
def throttled(self, request, wait):
"""
If request is throttled, determine what kind of exception to raise.
"""
class MyThrottled(exceptions.Throttled):
default_detail = '请求被限制.'
extra_detail_singular = 'Expected available in {wait} second.'
extra_detail_plural = '还需要再等待{wait}'
raise MyThrottled(wait)
Django REST framework之throttle节流原理
最新推荐文章于 2021-05-20 21:10:09 发布