自定义节流问题

Custom throttling problems

我有:

class Phone(models.Model):
    code = models.CharField(max_length=5)
    verification = models.UUIDField(default=uuid.uuid4, unique=True)

在我的视图集中,我必须通过他的验证来限制从设备到我的端点的请求数量。

class MyViewSet(viewsets.GenericViewSet):
      permission_classes = (permissions.AllowAny,)
      throttle_classes = (UserPhoneThrottle,)

      serializer_class_map = {
          ...,
          'verify': serializers.VerifyCodeSerializer,
      }

我试着写我的自定义油门:

class UserPhoneThrottle(throttling.SimpleRateThrottle):

    def get_cache_key(self, request, view):
        verification_id = request.data.get('verification_id')

        if not verification_id:
             return None
        else:
             return self.cache_format % {
                 'scope': self.scope,
                 'ident': verification_id
             }

在我的设置中:

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
         'app.throttling.UserPhoneThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        ...?
     }
}

求助或协助正确完成给定的逻辑并提示这是什么错误:

django.core.exceptions.ImproperlyConfigured: You must set either .scope or .rate for 'UserPhoneThrottle' throttle

我将非常感谢您的帮助。谢谢!)

错误很漂亮直截了当,

你应该或者settings.py中设置这样的东西,

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'app.throttling.UserPhoneThrottle',
    ),
    <b>'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }</b>
}



UserPhoneThrottle 中设置 .scope 作为,

class UserPhoneThrottle(throttling.SimpleRateThrottle):
    <b>scope = 'user'</b>
    # your code