guzhi/app/services/rate_limiter.py
邹方成 cc352d3184 feat: 重构后端服务并添加新功能
refactor: 优化API路由和响应模型
feat(admin): 添加App用户管理接口
feat(sms): 实现阿里云短信服务集成
feat(email): 添加SMTP邮件发送功能
feat(upload): 支持文件上传接口
feat(rate-limiter): 实现手机号限流器
fix: 修复计算步骤入库问题
docs: 更新API文档和测试计划
chore: 更新依赖和配置
2025-11-19 19:36:03 +08:00

52 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import time
from typing import Dict
class PhoneRateLimiter:
def __init__(self, window_seconds: int = 60) -> None:
"""手机号限流器
Args:
window_seconds: 限流窗口秒数
Returns:
None
"""
self.window = window_seconds
self.last_sent: Dict[str, float] = {}
def allow(self, phone: str) -> bool:
"""校验是否允许发送
Args:
phone: 手机号
Returns:
True 表示允许发送False 表示命中限流
"""
now = time.time()
ts = self.last_sent.get(phone, 0)
if now - ts < self.window:
return False
self.last_sent[phone] = now
return True
def next_allowed_at(self, phone: str) -> float:
"""返回下一次允许发送的时间戳
Args:
phone: 手机号
Returns:
时间戳(秒)
"""
ts = self.last_sent.get(phone, 0)
return ts + self.window
def reset(self) -> None:
"""重置限流状态
Returns:
None
"""
self.last_sent.clear()