限流:对接口访问的频次进行限制,以减轻服务器压力或者实现特定的业务。一般用于付费购买次数、投票等场景使用。
配置方式有两种:全局配置和局部配置。
1、全局配置
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.AnonRateThrottle", # 未认证用户
"rest_framework.throttling.UserRateThrottle", # 已认证用户
],
"DEFAULT_THROTTLE_RATES": { # 频率配置
"anon": "2/min", # 匿名用户每分钟最多访问 2 次
"user": "10/min", # 认证用户每分钟最多访问 10 次
},
}
2、测试
2、局部配置
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
# "DEFAULT_THROTTLE_CLASSES": [
# "rest_framework.throttling.AnonRateThrottle", # 未认证用户
# "rest_framework.throttling.UserRateThrottle", # 已认证用户
# ],
"DEFAULT_THROTTLE_RATES": { # 频率配置
"anon": "2/min", # 匿名用户每分钟最多访问 2 次
"user": "5/min", # 认证用户每分钟最多访问 10 次
},
}
3、视图类里views.py配置
from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (
ListModelMixin,
CreateModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
DestroyModelMixin,
)
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from rest_framework.authentication import (
BasicAuthentication,
SessionAuthentication,
)
from rest_framework.permissions import (
IsAuthenticated,
AllowAny,
IsAuthenticatedOrReadOnly,
)
from .models import *
from api.serializer import *
from rest_framework.throttling import UserRateThrottle
# 这种写法实现所有的增删改查,不能够单独进行操作
# class Linkapi(ModelViewSet):
# 不仅可以实现所有的增删改查,而且可以单独也可以全部包含增删改查
class Linkapi(
GenericViewSet,
ListModelMixin,
CreateModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
DestroyModelMixin,
):
queryset = Link.objects.all()
serializer_class = LinkSerializer
# authentication_classes = [SessionAuthentication]
# IsAuthenticated 授权登录后可以访问
# IsAuthenticatedOrReadOnly 只允许查询
permission_classes = [IsAuthenticatedOrReadOnly]
# 限流局部配置
throttle_classes = [UserRateThrottle]
4、用户也可以自定义限流,这个用AI去找demo即可。
5、代码下载
链接: https://pan.baidu.com/s/15Sro9DZHMDdPtYaJ7418mQ?pwd=gfwn 提取码: gfwn