rest_framework08:分页器/根据ip进行频率限制
生活随笔
收集整理的這篇文章主要介紹了
rest_framework08:分页器/根据ip进行频率限制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
分頁器
# 查詢所有,才需要分頁 from rest_framework.generics import ListAPIView# 內置三種分頁方式 from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination ''' PageNumberPagination ''' class MyPageNumberPagination(PageNumberPagination):page_size = 3 # 每頁條數page_query_param = 'aaa' #查詢第幾頁的keypage_size_query_param = 'size' # 每一項顯示的條數,用來自定義條數的名稱 ?aaa=2&size=6max_page_size = 5 # 每頁最大顯示條數,用來自定義條數# # 偏移計算的 # class MyLimitOffsetPagination(LimitOffsetPagination): # default_limit = 3 # 每頁條數 # limit_query_param = 'limit' # 往后拿幾條 # offset_query_param = 'offset' # 標桿 (偏移?) # max_limit = 5 # # class MyCursorPagination(CursorPagination): # cursor_query_param = 'cursor' # page_size = 2 # ordering = '-id' # 排序字段class BookView(ListAPIView):queryset = models.Book.objects.all().order_by('id')serializer_class = BookModelSerializer# 配置分頁pagination_class = MyPageNumberPagination# 使用APIView分頁 class BookView2(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進行頻率限制
1.寫一個類,繼承SimpleRateThrottle,需要重寫get_cache_key
get_cache_key返回什么就是限制什么,如ip
from rest_framework.throttling import SimpleRateThrottleclass MyThrottle(SimpleRateThrottle):scope = 'xxoo'def get_cache_key(self, request, view):print(request.META.get('REMOTE_ADDR'))return request.META.get('REMOTE_ADDR')2. settings設置頻率限制
REST_FRAMEWORK = {'DEFAULT_THROTTLE_RATES': {'xxoo': '3/m',} }局部設置
from utils.throttling import MyThrottle class BookView2(APIView):throttle_classes = [MyThrottle,]全局設置
REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': ('utils.throttling.MyThrottle', ),'DEFAULT_THROTTLE_RATES': {'xxoo': '3/m',} }總結
以上是生活随笔為你收集整理的rest_framework08:分页器/根据ip进行频率限制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rest_framework07:权限/
- 下一篇: rest_framework09:自动生