限流的使用
配置
可以在配置文件中,使用
DEFAULT_THROTTLE_CLASSES
和DEFAULT_THROTTLE_RATES
进行全局配置REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } }
可选限流类
AnonRateThrottle
- 限制所有匿名未认证用户,使用IP区分用户
- 使用
DEFAULT_THROTTLE_RATES['anon']
来设置频次
UserRateThrottle
- 限制认证用户,使用
User id
来区分 - 使用
DEFAULT_THROTTLE_RATES['user']
来设置频次
- 限制认证用户,使用
ScopedRateThrottle
限制用户对于每个视图的访问频次,使用
ip
或user id
配置文件
settings.py
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', 'uploads': '20/day' } }
限流类
class ContactListView(APIView): throttle_scope = 'contacts' # 业务逻辑 pass class ContactDetailView(APIView): throttle_scope = 'contacts' # 业务逻辑 pass class UploadView(APIView): throttle_scope = 'uploads' # 业务逻辑 pass
示例
from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.generics import RetrieveAPIView from rest_framework.throttling import UserRateThrottle class BookDetailView(RetrieveAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] throttle_classes = (UserRateThrottle,) def get(self,request,*args,**kwargs): return self.retrieve(request,*args,**kwargs)
DEFAULT_THROTTLE_RATES
可以使用second
,minute
,hour
或day
来指明周期。 也可以在具体视图中通过throttle_classess属性来配置,如from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView class ExampleView(APIView): throttle_classes = (UserRateThrottle,) pass