ratelimit.py 651 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env python3
  2. import time
  3. class rateLimit: # rate limit like iptables limit (per minutes)
  4. tLast = None
  5. def __init__(self, _rate_limit, _rate_burst):
  6. self.rate_limit = _rate_limit
  7. self.rate_burst = _rate_burst
  8. self.bucket = _rate_burst
  9. def limit(self):
  10. tNow = time.time()
  11. if self.tLast is None:
  12. self.tLast = tNow
  13. return True
  14. tDiff = tNow - self.tLast
  15. self.tLast = tNow
  16. self.bucket += (tDiff / (60 / self.rate_limit))
  17. if self.bucket > self.rate_burst:
  18. self.bucket = self.rate_burst
  19. if self.bucket >= 1:
  20. self.bucket-= 1
  21. return True
  22. else:
  23. return False