limiter.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from fastapi import FastAPI
  2. from slowapi import Limiter, _rate_limit_exceeded_handler
  3. from slowapi.errors import RateLimitExceeded
  4. from slowapi.util import get_remote_address
  5. import glovar
  6. from services.robot import send_msg
  7. from services.utils import current_date
  8. LIMITER = Limiter(key_func=get_remote_address)
  9. MAX_LIMIT = glovar.lm_max_limit
  10. def limit_exceeded_handler(*args, **kwargs):
  11. if glovar.lm_exceeded_warning:
  12. msg = "今日接口调用次数已达上限!\n 继续使用请点击"
  13. send_msg('超级鹰', MAX_LIMIT, MAX_LIMIT, msg, allow_reset=True)
  14. glovar.lm_exceeded_warning = False
  15. return _rate_limit_exceeded_handler(*args, **kwargs)
  16. def register_limiter(app: FastAPI):
  17. app.state.limiter = LIMITER
  18. app.add_exception_handler(RateLimitExceeded, limit_exceeded_handler)
  19. def flush_limiter():
  20. glovar.lm_counter = 0
  21. glovar.lm_forecast_warning = True
  22. glovar.lm_exceeded_warning = True
  23. def limiter_warring():
  24. platform = '超级鹰'
  25. curr_date = current_date()
  26. if curr_date != glovar.lm_date:
  27. if glovar.lm_date is not None:
  28. flush_limiter()
  29. glovar.lm_counter += 1
  30. glovar.lm_date = curr_date
  31. val = '{:.2f}'.format(glovar.lm_counter / MAX_LIMIT * 100)
  32. if float(val) > 80 and glovar.lm_forecast_warning:
  33. msg = f'使用次数已超过{val}%'
  34. send_msg(platform, MAX_LIMIT, glovar.lm_counter, msg)
  35. glovar.lm_forecast_warning = False