[英]How to set different throttle scopes for different users using django rest framework?
例如:为客户和员工设置不同的节流率。 这可以使用UserRateThrottle
来完成吗? 例如:
REST_FRAMEWORK['DEFAULT_THROTTLE_CLASSES'] = ('backend.throttles.EmployeeThrottle')
REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] = {
'user': config.THROTTLE_RATE,
'employee': config.EMPLOYEE_THROTTLE_RATE
}
from rest_framework.throttling import UserRateThrottle
class EmployeeThrottle(UserRateThrottle):
*WHAT TO DO HERE?*
我可以在这个EmployeeThrottle
类中以某种方式获取请求并根据该请求内容设置范围。
编辑:例如: UserRateThrottle这里BurstRateThrottle
,如果不知何故,我能得到我的请求可以设置基于该范围。
如果这是每个用户类型,那么您应该使用BaseThrottle
作为基类。 我认为这样的事情应该有效吗?
class UserRateThrottle(throttling.BaseThrottle):
scope = 'user'
def allow_request(self, request, view):
return request.user.type == 'user'
class EmployeeRateThrottle(throttling.BaseThrottle):
scope = 'employee'
def allow_request(self, request, view):
return request.user.type == 'employee'
from rest_framework.throttling import UserRateThrottle
class CustomThrottle(UserRateThrottle):
def __init__(self):
pass
def allow_request(self, request, view):
employee_scope = getattr(view, 'employee', None)
user_scope = getattr(view, 'user', None)
if request.user.profile.is_employee:
if not employee_scope:
return True
self.scope = employee_scope
else:
if not user_scope:
return True
self.scope = user_scope
self.rate = self.get_rate()
self.num_requests, self.duration = self.parse_rate(self.rate)
return super().allow_request(request, view)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.