DRF限流算法

编程

class SimpleRateThrottle(BaseThrottle):

def allow_request(self, request, view):

"""

Implement the check to see if the request should be throttled.

On success calls `throttle_success`.

On failure calls `throttle_failure`.

"""

if self.rate is None:

return True

self.key = self.get_cache_key(request, view)

if self.key is None:

return True

self.history = self.cache.get(self.key, [])

self.now = self.timer()

# Drop any requests from the history which have now passed the

# throttle duration

while self.history and self.history[-1] <= self.now - self.duration:

self.history.pop()

if len(self.history) >= self.num_requests:

return self.throttle_failure()

return self.throttle_success()

流程

1. api dispatch 流程

    self.initial(request, *args, **kwargs)

self.perform_authentication(request)

self.check_permissions(request)

self.check_throttles(request)

2. 限流算法流程

  • 通过get_cache_key 获取cache 中限流的key对应的history请求时间戳.
  • 根据self.now - self.duration, 移除过期的hostory中的时间戳.
  • 判断访问频率是否大于限制策略

	if len(self.history) >= self.num_requests:

return self.throttle_failure()

return self.throttle_success()

以上是 DRF限流算法 的全部内容, 来源链接: utcz.com/z/514959.html

回到顶部