分页器和自定义限制ip访问频率
分页器和自定义限制ip访问频率
分页器
第一种PageNumberPagination
#views.py
# 查所有,才需要分页
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination,
'''
PageNumberPagination
page_size:每页显示的条数
'''
class MyPageNumberPagination(PageNumberPagination):
page_size=3 #每页条数
page_query_param='aaa' #查询第几页的key
page_size_query_param='size' # 每一页显示的条数
max_page_size=5 # 每页最大显示条数
url:#http://127.0.0.1:8000/api/books2/?aaa=1&size=6
第二种LimitOffsetPagination
from rest_framework.pagination import LimitOffsetPagination
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 3 # 每页条数
limit_query_param = 'limit' # 往后拿几条
offset_query_param = 'offset' # 标杆
max_limit = 5 # 每页最大几条
第三种CursorPagination
from rest_framework.pagination import CursorPagination
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor' # 每一页查询的key
page_size = 2 #每页显示的条数
ordering = '-id' #排序字段
view视图
class BookView(ListAPIView):
# queryset = models.Book.objects.all().filter(is_delete=False)
queryset = models.Book.objects.all()
serializer_class = BookModelSerializer
#配置分页
pagination_class = MyCursorPagination
因为分页器是GenericAPIView的方法,APIView里面没有
APIView使用分页器
class MyPageNumberPagination(PageNumberPagination):
page_size=3 #每页条数
page_query_param='aaa' #查询第几页的key
page_size_query_param='size' # 每一页显示的条数
max_page_size=5 # 每页最大显示条数
class BookView(APIView):
def get(self,request,*args,**kwargs):
book_list=models.Book.objects.all()
# 实例化得到一个分页器对象
page_cursor=MyPageNumberPagination()
book_list=page_cursor.paginate_queryset(book_list,request,view=self)
next_url =page_cursor.get_next_link()
pr_url=page_cursor.get_previous_link()
book_ser=BookModelSerializer(book_list,many=True)
return Response(data=book_ser.data)
自定义ip频率访问
# 自定制频率类,需要写两个方法
-# 判断是否限次:没有限次可以请求True,限次了不可以请求False
def allow_request(self, request, view):
-# 限次后调用,显示还需等待多长时间才能再访问,返回等待的时间seconds
def wait(self):
# 代码
import time
class IPThrottle():
#定义成类属性,所有对象用的都是这个
VISIT_DIC = {}
def __init__(self):
self.history_list=[]
def allow_request(self, request, view):
'''
#(1)取出访问者ip
#(2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
#(3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
#(4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
#(5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
'''
ip=request.META.get('REMOTE_ADDR')
ctime=time.time()
if ip not in self.VISIT_DIC:
self.VISIT_DIC[ip]=[ctime,]
return True
self.history_list=self.VISIT_DIC[ip] #当前访问者时间列表拿出来
while True:
if ctime-self.history_list[-1]>60:
self.history_list.pop() # 把最后一个移除
else:
break
if len(self.history_list)<3:
self.history_list.insert(0,ctime)
return True
else:
return False
def wait(self):
# 当前时间,减去列表中最后一个时间
ctime=time.time()
return 60-(ctime-self.history_list[-1])
#全局使用,局部使用
源码分析
# SimpleRateThrottle源码分析
def get_rate(self):
"""
Determine the string representation of the allowed request rate.
"""
if not getattr(self, 'scope', None):
msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
self.__class__.__name__)
raise ImproperlyConfigured(msg)
try:
return self.THROTTLE_RATES[self.scope] # scope:'user' => '3/min'
except KeyError:
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)
def parse_rate(self, rate):
"""
Given the request rate string, return a two tuple of:
<allowed number of requests>, <period of time in seconds>
"""
if rate is None:
return (None, None)
#3 mmmmm
num, period = rate.split('/') # rate:'3/min'
num_requests = int(num)
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
return (num_requests, duration)
def allow_request(self, request, view):
if self.rate is None:
return True
#当前登录用户的ip地址
self.key = self.get_cache_key(request, view) # key:'throttle_user_1'
if self.key is None:
return True
# 初次访问缓存为空,self.history为[],是存放时间的列表
self.history = self.cache.get(self.key, [])
# 获取一下当前时间,存放到 self.now
self.now = self.timer()
# Drop any requests from the history which have now passed the
# throttle duration
# 当前访问与第一次访问时间间隔如果大于60s,第一次记录清除,不再算作一次计数
# 10 20 30 40
# self.history:[10:23,10:55]
# now:10:56
while self.history and self.now - self.history[-1] >= self.duration:
self.history.pop()
# history的长度与限制次数3进行比较
# history 长度第一次访问0,第二次访问1,第三次访问2,第四次访问3失败
if len(self.history) >= self.num_requests:
# 直接返回False,代表频率限制了
return self.throttle_failure()
# history的长度未达到限制次数3,代表可以访问
# 将当前时间插入到history列表的开头,将history列表作为数据存到缓存中,key是throttle_user_1,过期时间60s
return self.throttle_success()