Skip to content

Commit 9c6077b

Browse files
author
JiayuXu
committed
fix: load slowapi env with utf8 fallback
1 parent 3ec90c1 commit 9c6077b

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

src/api/v1/base/base.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import locale
12
import os
23
import platform
34
from datetime import UTC, datetime
45

56
from fastapi import APIRouter, HTTPException, Request
67
from slowapi import Limiter
8+
from slowapi import extension as slowapi_extension
79
from slowapi.util import get_remote_address
10+
from starlette.config import Config as StarletteConfig
811

912
from core.ctx import CTX_USER_ID
1013
from core.dependency import DependAuth
@@ -21,7 +24,37 @@
2124
from settings import settings
2225
from utils.jwt import create_token_pair, verify_token
2326

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+
2558
limiter = Limiter(key_func=get_remote_address)
2659

2760
router = APIRouter()

0 commit comments

Comments
 (0)