官方文檔:https://www.django-rest-framework.org/api-guide/throttling/django
一、什麼場景下須要限制訪問頻次呢?api
1)防爬蟲:爬蟲可能會在短期內大量的訪問服務接口,增長服務器壓力服務器
2)對於須要限制訪問頻次的接口ide
二、DRF如何限速:函數
經過 rest_framework下面的throttling 模塊實現ui
throttling模塊主要提供了三種限速方式:spa
1)AnonRateThrottle3d
針對未登陸用戶的限速,經過IP地址區分用戶rest
2)UserRateThrottle:code
針對已登陸用戶,經過user id來區分用戶
3)ScopedRateThrottle:
限制用於對於每一個視圖的訪問頻次,經過ip地址或者useid來區分
使用方法:
1)在配置文件中配置須要使用什麼類型的限速,以及限制的訪問頻次
訪問頻次單位有:second,minute,hour和day
2)在對應的視圖函數中使用
throttle_classes = (AnonRateThrottle,)
from rest_framework.throttling import AnonRateThrottle class GoodListView(APIView): throttle_classes = (AnonRateThrottle,) @cache_response(cache_errors=False) def get(self, request, format=None): print(request.query_params) goods = Goods.objects.all()[:10] goods_serializer = GoodListSerializer1(goods, many=True) return Response(goods_serializer.data)
3)使用裝飾器
@throttle_class([AnonRateThrottle,])
from rest_framework.decorators import throttle_classes @throttle_classes([AnonRateThrottle,]) class GoodListView(APIView): # throttle_classes = (AnonRateThrottle,) @cache_response(cache_errors=False) def get(self, request, format=None): print(request.query_params) goods = Goods.objects.all()[:10] goods_serializer = GoodListSerializer1(goods, many=True) return Response(goods_serializer.data)
4)對於ScopedRateThrottle,可用於限制訪問指定的API,僅當訪問的視同中包含 throttle_scope屬性時,纔會應用此限制
class ContactListView(APIView): throttle_scope = 'contacts' pass class ContactDetailView(APIView): throttle_scope = 'contacts' pass class UploadView(APIView): throttle_scope = 'uploads' pass
而後在settings中配置以下:
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', 'uploads': '20/day' } }
在上面的視圖中,ContactListView和ContactDetailView兩個視圖中,throttle_scope都是contacts,settings中,設置的contacts頻率限制爲1000次天天,因此ContactListView和ContactDetailView兩個視圖函數加起來一天的訪問次數不能超過1000次
UploadView的訪問次數,不能超過20次天天