分页器

# 查询所有,才需要分页
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'  #查询第几页的key
    page_size_query_param = 'size' # 每一项显示的条数,用来自定义条数的名称 ?aaa=2&size=6
    max_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 SimpleRateThrottle


class 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',
    }
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐