rest-framework频率组件、url注册器、响应器、分页器
频率组件
1 import time 2 3 from rest_framework.throttling import BaseThrottle,SimpleRateThrottle 4 5 6 IP_DICT = {} 7 class Throttling(BaseThrottle): 8 9 def __init__(self): 10 self.history = None 11 12 def allow_request(self, request, view): 13 ctime = time.time() 14 remote_addr = request.META.get("REMOTE_ADDR") 15 16 if remote_addr not in IP_DICT: 17 IP_DICT[remote_addr] = [ctime] 18 return True 19 20 history = IP_DICT[remote_addr] 21 self.history = history 22 23 while history and history[-1] < ctime - 60: 24 history.pop() 25 26 if len(history) < 3: 27 history.insert(0, ctime) 28 return True 29 30 31 def wait(self): 32 ctime = time.time() 33 return 60 - (ctime - self.history[-1])
在使用的视图类中加入:
throttle_classes = [Throttling]
继承一个简单的频率类
1 class SimpleThrottling(SimpleRateThrottle): 2 3 rate = "5/m" #局部配置 4 # scope = "visit_rate" #全局配置 5 6 def get_cache_key(self, request, view): 7 return self.get_ident(request)
全局配置
1 REST_FRAMEWORK = { 2 'DEFAULT_THROTTLE_CLASSES': ( 3 "app01.utils.app_throttle.SimpleThrottling", 4 ), 5 'DEFAULT_THROTTLE_RATES': { 6 "visit_rate": "5/m" 7 } 8 }
局部配置
1 throttle_classes = [SimpleThrottling]
url注册器
1 from django.contrib import admin 2 from django.urls import path,re_path,include 3 4 from rest_framework import routers 5 6 from app01 import views 7 8 router = routers.DefaultRouter() 9 router.register("books",views.BookView) 10 11 urlpatterns = [ 12 path('admin/', admin.site.urls), 13 14 15 # path('books/', views.BookView.as_view()), 16 # re_path('books/(?P<pk>\d+)/', views.BookFilterView.as_view()), 17 18 # path('books/', views.BookView.as_view({ 19 # 'get':'list', 20 # "post":"create" 21 # })), 22 # re_path('books/(?P<pk>\d+)/', views.BookView.as_view({ 23 # "get":"retrieve", 24 # "put":"update", 25 # "delete":"destroy" 26 # })), 27 re_path("^",include(router.urls)), 28 path('user/',views.UserView.as_view()) 29 ]
响应器
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer renderer_classes = [JSONRenderer] #之支持json格式的渲染,而不支持浏览器的渲染
分页器
1 # 自定义一个分页器类 2 from rest_framework.pagination import PageNumberPagination 3 4 5 class MyPagonation(PageNumberPagination): 6 page_size = 3 全局配置"PAGE_SIZE" 7 page_query_param = "page" 8 page_size_query_param = "size" 9 max_page_size = 5
局部配置
pagination_class = MyPagonation