|
| 1 | +import locale |
1 | 2 | import os |
2 | 3 | import platform |
3 | 4 | from datetime import UTC, datetime |
4 | 5 |
|
5 | 6 | from fastapi import APIRouter, HTTPException, Request |
6 | 7 | from slowapi import Limiter |
| 8 | +from slowapi import extension as slowapi_extension |
7 | 9 | from slowapi.util import get_remote_address |
| 10 | +from starlette.config import Config as StarletteConfig |
8 | 11 |
|
9 | 12 | from core.ctx import CTX_USER_ID |
10 | 13 | from core.dependency import DependAuth |
|
21 | 24 | from settings import settings |
22 | 25 | from utils.jwt import create_token_pair, verify_token |
23 | 26 |
|
24 | | -# 创建限流器实例 |
| 27 | +class AdaptiveEnvConfig(StarletteConfig): |
| 28 | + def _read_file(self, file_name): |
| 29 | + encodings = ["utf-8", "utf-8-sig"] |
| 30 | + preferred = locale.getpreferredencoding(do_setlocale=False) |
| 31 | + if preferred and preferred.lower() not in (e.lower() for e in encodings): |
| 32 | + encodings.append(preferred) |
| 33 | + encodings.append("latin-1") # final fallback to avoid UnicodeDecodeError |
| 34 | + |
| 35 | + last_error: UnicodeDecodeError | None = None |
| 36 | + for encoding in encodings: |
| 37 | + try: |
| 38 | + file_values: dict[str, str] = {} |
| 39 | + with open(file_name, encoding=encoding) as input_file: |
| 40 | + for line in input_file.readlines(): |
| 41 | + line = line.strip() |
| 42 | + if "=" in line and not line.startswith("#"): |
| 43 | + key, value = line.split("=", 1) |
| 44 | + key = key.strip() |
| 45 | + value = value.strip().strip("\"'") |
| 46 | + file_values[key] = value |
| 47 | + return file_values |
| 48 | + except UnicodeDecodeError as exc: |
| 49 | + last_error = exc |
| 50 | + if last_error: |
| 51 | + raise last_error |
| 52 | + return {} |
| 53 | + |
| 54 | + |
| 55 | +if getattr(slowapi_extension.Config, "__name__", "") != "AdaptiveEnvConfig": |
| 56 | + slowapi_extension.Config = AdaptiveEnvConfig |
| 57 | + |
25 | 58 | limiter = Limiter(key_func=get_remote_address) |
26 | 59 |
|
27 | 60 | router = APIRouter() |
|
0 commit comments