from django.core.exceptions import ImproperlyConfigured from rest_framework.exceptions import APIException from rest_framework.throttling import SimpleRateThrottle class ThrottleBase(SimpleRateThrottle): """ 接口访问频率限制基类 """ throttled_message = '请求评率超过限制' rate = '3/m' def get_cache_key(self, request, view): super().get_cache_key(request, view) def allow_request(self, request, view): flag = super().allow_request(request, view) if not flag: raise APIException(detail=self.throttled_message, code=500) return flag def get_rate(self): """ Determine the string representation of the allowed request rate. """ if not getattr(self, 'scope', None): msg = ("You must set either `.scope` or `.rate` for '%s' throttle" % self.__class__.__name__) raise ImproperlyConfigured(msg) return self.rate class PhoneCodeThrottle(ThrottleBase): rate = '1/m' scope = "phone_code" throttled_message = "您的请求频率过快,请稍后再试。" def get_cache_key(self, request, view): return self.cache_format % { 'scope': self.scope, 'ident': f"{request.data.get('mobile')}-{request.data.get('business')}" }