python - Django Rest Framework Scope Throttling on function based view
问题描述
想问是否有人知道如何在基于函数的视图中为不同的请求方法设置不同的节流范围的方法或解决方法。
例如
@api_view(['GET', 'POST'])
def someFunction(request):
if request.method == 'GET':
# set scope for get requests
elif request.method == 'POST':
# set scope for post requests
我试着环顾四周,但所有答案都只针对基于类的视图。不胜感激,谢谢。
解决方案
您可以通过首先创建所有自定义限制类来解决此问题。注意:只有油门在类中,但视图是函数。
class PostAnononymousRateThrottle(throttling.AnonRateThrottle):
scope = 'post_anon'
def allow_request(self, request, view):
if request.method == "GET":
return True
return super().allow_request(request, view)
class GetAnononymousRateThrottle(throttling.AnonRateThrottle):
scope = 'get_anon'
def allow_request(self, request, view):
if request.method == "POST":
return True
return super().allow_request(request, view)
class PostUserRateThrottle(throttling.UserRateThrottle):
scope = 'post_user'
def allow_request(self, request, view):
if request.method == "GET":
return True
return super().allow_request(request, view)
class GetUserRateThrottle(throttling.UserRateThrottle):
scope = 'get_user'
def allow_request(self, request, view):
if request.method == "POST":
return True
return super().allow_request(request, view)
如果您不是在寻找身份验证或方法类型,则可以选择消除这些类。
然后你需要导入这个
from rest_framework.decorators import api_view, throttle_classes
然后,您可以使用创建的所有权限的 throttle_classes 装饰器包装您的函数视图
@api_view(['GET', 'POST'])
@throttle_classes([PostAnononymousRateThrottle, GetAnononymousRateThrottle, PostUserRateThrottle, GetUserRateThrottle])
def someFunction(request):
if request.method == 'POST':
return Response({"message": "Got some data!", "data": request.data})
elif request.method == 'GET':
return Response({"message": "Hello, world!"})
不要忘记在 settings.py 中提及油门速率
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'post_anon': '3/minute',
'get_anon': '1/minute',
'post_user': '2/minute',
'get_user': '2/minute'
}
}
推荐阅读
- vue.js - 有条件地隐藏 v-data-table 中的列(Vuetify)
- angular - Electron-dl 下载在打包的应用程序中不起作用
- sql - 在将 JSON 列转换为 SQL 表时需要帮助
- c++ - 为什么 ASIO 会同时关闭 2 个 TCP 连接?
- c# - Unity不会一键破坏对象
- android - 如何在容器内居中行?- 颤振
- time - 计算航海者一号往返通信时间的函数
- android - Android 交付需要 FcmNotification 属性?
- java - 带有路径变量的 URL 模式的 Spring 过滤器
- c - 为什么原始 udp 数据包不遵循路由规则