我正在尝试编写一个API,它将接收一个字符串或字符串列表,并返回模型的预测结果。我使用令牌身份验证是为了方便使用,然而,我不明白/无法想象我如何限制用户每月可以发出的请求量。或者向匿名用户发出有限数量的请求。是否应该创建自定义权限类?
### settings.py ##
INSTALLED_APPS = [
# basics
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# API
'rest_framework',
'rest_framework.authtoken', # auth
'rest_framework_tracking', # logging
]
## views.py ##
class MyAPIView(APIView, LoggingMixin):
logging_methods = ['POST', 'PUT']
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [BrowsableAPIRenderer, JSONRenderer, CSVRenderer]
parser_classes = [JSONParser, MultiPartParser]
def post(self, request, proba=False):
query = request.POST.get('q')
content = {
'result': "Model predictions."
}
return Response(content, status=status.HTTP_200_OK)
发布于 2020-09-07 19:55:58
存在节流,您可以使用默认节流率,也可以创建自定义节流率。
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
}
您可以在您的API中使用这些速率。
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
class ExampleView(APIView):
throttle_classes = [UserRateThrottle]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
我想这篇文档可能会对你有所帮助,https://www.django-rest-framework.org/api-guide/throttling/
https://stackoverflow.com/questions/63758443
复制相似问题