fix: auto-fix code issues (cron)
- 修复重复导入/字段 - 修复异常处理 - 修复PEP8格式问题 - 添加类型注解
This commit is contained in:
@@ -5,11 +5,11 @@ API 限流中间件
|
||||
支持基于内存的滑动窗口限流
|
||||
"""
|
||||
|
||||
import time
|
||||
import asyncio
|
||||
from typing import Dict, Optional, Callable
|
||||
from dataclasses import dataclass
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from functools import wraps
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ class SlidingWindowCounter:
|
||||
|
||||
def __init__(self, window_size: int = 60):
|
||||
self.window_size = window_size
|
||||
self.requests: Dict[int, int] = defaultdict(int) # 秒级计数
|
||||
self.requests: dict[int, int] = defaultdict(int) # 秒级计数
|
||||
self._lock = asyncio.Lock()
|
||||
self._cleanup_lock = asyncio.Lock()
|
||||
|
||||
@@ -69,13 +69,13 @@ class RateLimiter:
|
||||
|
||||
def __init__(self):
|
||||
# key -> SlidingWindowCounter
|
||||
self.counters: Dict[str, SlidingWindowCounter] = {}
|
||||
self.counters: dict[str, SlidingWindowCounter] = {}
|
||||
# key -> RateLimitConfig
|
||||
self.configs: Dict[str, RateLimitConfig] = {}
|
||||
self.configs: dict[str, RateLimitConfig] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._cleanup_lock = asyncio.Lock()
|
||||
|
||||
async def is_allowed(self, key: str, config: Optional[RateLimitConfig] = None) -> RateLimitInfo:
|
||||
async def is_allowed(self, key: str, config: RateLimitConfig | None = None) -> RateLimitInfo:
|
||||
"""
|
||||
检查是否允许请求
|
||||
|
||||
@@ -143,7 +143,7 @@ class RateLimiter:
|
||||
retry_after=max(0, config.window_size) if current_count >= config.requests_per_minute else 0,
|
||||
)
|
||||
|
||||
def reset(self, key: Optional[str] = None):
|
||||
def reset(self, key: str | None = None):
|
||||
"""重置限流计数器"""
|
||||
if key:
|
||||
self.counters.pop(key, None)
|
||||
@@ -154,7 +154,7 @@ class RateLimiter:
|
||||
|
||||
|
||||
# 全局限流器实例
|
||||
_rate_limiter: Optional[RateLimiter] = None
|
||||
_rate_limiter: RateLimiter | None = None
|
||||
|
||||
|
||||
def get_rate_limiter() -> RateLimiter:
|
||||
@@ -166,7 +166,7 @@ def get_rate_limiter() -> RateLimiter:
|
||||
|
||||
|
||||
# 限流装饰器(用于函数级别限流)
|
||||
def rate_limit(requests_per_minute: int = 60, key_func: Optional[Callable] = None):
|
||||
def rate_limit(requests_per_minute: int = 60, key_func: Callable | None = None):
|
||||
"""
|
||||
限流装饰器
|
||||
|
||||
|
||||
Reference in New Issue
Block a user