DRF - 通过内置函数实现访问频率
在 app 目录下的 utils 目录下创建 throttle.py
throttle.py:
from rest_framework.throttling import SimpleRateThrottle
import time
# 访问记录
VISIT_RECORD = {}
# 用于游客的访问控制
class VisitThrottle(SimpleRateThrottle):
# 设置 settings.py 中访问频率的字典的 key
scope = "anonymous" # 获取设定的访问频率
def get_cache_key(self, request, view):
# 取 IP 地址作为访问记录 VISIT_RECORD 的标识 key
return self.get_ident(request)
# 用于用户的访问控制
class UserThrottle(SimpleRateThrottle):
# 设置 settings.py 中访问频率的字典的 key
scope = "user" # 获取设定的访问频率
def get_cache_key(self, request, view):
# 取用户名作为访问记录 VISIT_RECORD 的标识 key
return request.user.username
auth.py:
from rest_framework.authentication import BaseAuthentication
from drf import models
from rest_framework.exceptions import AuthenticationFailed
# 用于全局认证
class GlobalAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request._request.GET.get("token")
token_obj = models.UserToken.objects.filter(token=token).first()
if not token_obj:
raise AuthenticationFailed("用户认证失败")
return (token_obj.user, None)
def authenticate_header(self, request):
pass
settings.py 中设置全局访问频率类和访问频率
REST_FRAMEWORK = {
# 全局使用的认证类
"DEFAULT_AUTHENTICATION_CLASSES": ["drf.utils.auth.GlobalAuthentication", ],
# 全局使用的访问频率
"DEFAULT_THROTTLE_CLASSES": ["drf.utils.throttle.VisitThrottle"],
# 通过字典设置访问频率
"DEFAULT_THROTTLE_RATES":{
"anonymous": "3/m", # 每分钟 3 次
"user": "10/m", # 每分钟 10 次
}
}
关于设定的访问频率的时间

分别对应秒、分、时、天,/ 前为规定的数
views.py:
from django.http import JsonResponse
from rest_framework.views import APIView
from drf.utils.throttle import UserThrottle
ORDER_DICT = {
1: {
"commodity": "Phone",
"price": 3600,
"date": "2021-01-03",
},
2: {
"commodity": "Computer",
"price": 6700,
"date": "2021-01-05",
},
}
class OrderView(APIView):
"""
查看订单
"""
def get(self, request, *args, **kwargs):
response = {"code": 1000, "msg": None, "data": None}
try:
response["data"] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(response)
USER_DICT = {
1: {
"name": "John",
"password": "John123",
"phone": "20210103",
},
2: {
"name": "Jack",
"password": "Jack456",
"phone": "20210105",
},
}
class UserinfoView(APIView):
"""
查看用户信息
"""
# 设置局部访问频率类
throttle_classes = [UserThrottle, ]
def get(self, request, *args, **kwargs):
response = {"code": 1000, "msg": None, "data": None}
try:
response["data"] = USER_DICT
except Exception as e:
pass
return JsonResponse(response)
访问 /userinfo/?token=b9d56bfaeba57885b63dd0081c97c1d2,1 分内访问 10 次后


浙公网安备 33010602011771号