【问题标题】:How to set different throttle scopes for different users using django rest framework?如何使用 django rest 框架为不同的用户设置不同的节流范围?
【发布时间】:2021-01-13 05:44:07
【问题描述】:

例如:为客户和员工设置不同的节流率。 这可以使用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 类中以某种方式获取请求并根据该请求内容设置范围。

编辑:例如:UserRateThrottleBurstRateThrottle 中,如果我能以某种方式获得请求,我可以根据它设置范围。

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    如果这是每个用户类型,那么您应该使用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'
    

    【讨论】:

    • DRF 如何知道设置哪个范围(调用哪个函数)。 UserRateThrottle 还是 EmployeeRateThrottle?
    • 它将通过视图中定义的范围名称 attr 和DEFAULT_THROTTLE_RATES 设置来获取它
    • 我不希望它逐个定义视图。我希望所有 API 都具有 user 油门或 employee 油门速率,具体取决于 request.user 类型。我想事先检查用户是客户还是员工。
    • 什么意思?您只需定义这两个类并将它们添加到DEFAULT_THROTTLE_CLASSES 设置中
    【解决方案2】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多