当前,我们的 Restful Web API 不仅能够提供客户端需要的资源,还实现了认证和权限,可以保证数据的安全。那么我们搭建的 Restful Web API 能实现类似的功能吗?当然可以,这就涉及到了限流与过滤,接下来,我们就带领大家,一起实现这两个功能。
1.限流的使用方法
有时,为了防止恶意访问,或减轻服务器压力,我们需要对用户的访问频率进行限制。我们可在配置文件中,使用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', # 匿名用户每天可访问100次
'user': '1000/day' # 通过认证的用户每天可访问1000次
}
}
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,)
...
2. Django Rest framework为我们提供的限流类
2.1 AnonRateThrottle
限制所有匿名未认证用户,不同用户的区分通过识别用户 IP 实现。使用DEFAULT_THRottLE_RATES['anon'] 来设置频率限制。
2.2 UserRateThrottle
限制认证用户,使用 User id 来区分不同用户。使用 DEFAULT_THRottLE_RATES['user'] 来设置频率限制。
2.3 ScopedrateThrottle
限制用户对于每个视图的访问频次,使用 ip 或 user id 区分不同用户。
例如:
class ContactListView(APIView):
throttle_scope = 'contacts'
...
class ContactDetailView(APIView):
throttle_scope = 'contacts'
...
class UploadView(APIView):
throttle_scope = 'uploads'
...
REST_FRAMEWORK = {
'DEFAULT_THRottLE_CLASSES': (
'rest_framework.throttling.ScopedrateThrottle',
),
'DEFAULT_THRottLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'
}
}
3.实例
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 StudentViewSet(ModelViewSet):
queryset = StudentsModel.objects.all()
serializer_class = StudentsSerializer
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
throttle_classes = (UserRateThrottle,)