fix: EXPECTED_API_KEY 改为惰性求值防加载顺序问题

This commit is contained in:
2026-07-10 15:27:38 +08:00
parent 29bdfcfb18
commit ebfae1f60c
3 changed files with 18 additions and 12 deletions
+12 -1
View File
@@ -18,7 +18,7 @@ dependencies = [
md-vector-db = "src.cli.main:app"
[project.optional-dependencies]
dev = ["pytest>=8.0", "httpx>=0.27.0"]
dev = ["pytest>=8.0", "httpx>=0.27.0", "pytest-cov>=5.0", "ruff>=0.8.0", "mypy>=1.13"]
pdf = ["pymupdf>=1.24.0"]
html = ["beautifulsoup4>=4.12.0"]
epub = ["ebooklib>=0.18"]
@@ -35,6 +35,17 @@ packages = ["src/"]
find-links = ["D:/settings/Language/Python/库"]
index-strategy = "unsafe-best-match"
[tool.ruff]
line-length = 100
target-version = "py313"
[tool.ruff.lint]
select = ["E", "F", "I", "N", "W"]
[tool.mypy]
python_version = "3.13"
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
+3 -2
View File
@@ -154,6 +154,7 @@ class DashscopeEmbedder(_BaseAPIEmbedder):
def embed(self, texts: list[str]) -> list[list[float]]:
if not texts:
raise ValueError("文本列表不能为空")
import requests # 惰性导入(仅 DashScope 使用)
resp = requests.post(
self._api_base,
headers={
@@ -176,8 +177,8 @@ class DashscopeEmbedder(_BaseAPIEmbedder):
if not isinstance(embeddings_raw, list):
raise ValueError(f"DashScope embeddings 不是列表: {type(embeddings_raw)}")
# 按 text_index 排序确保顺序
embeddings_raw.sort(key=lambda x: x.get("text_index", 0))
return [e["embedding"] for e in embeddings_raw]
embeddings_raw_sorted = sorted(embeddings_raw, key=lambda x: x.get("text_index", 0))
return [e["embedding"] for e in embeddings_raw_sorted]
# -- 工厂函数 --
+3 -9
View File
@@ -11,15 +11,9 @@ from fastapi import Header, HTTPException, Request
logger = logging.getLogger("md-vector-db")
# -- API Key 认证 --
_EXPECTED_API_KEY = os.environ.get("MD_VECTOR_API_KEY", "")
def _make_get_api_key():
"""创建从环境变量读取预期 API Key 的函数 (便于测试替换)."""
return lambda: _EXPECTED_API_KEY
_get_expected_api_key = _make_get_api_key()
def _get_expected_api_key() -> str:
"""惰性获取 API Key(每次调用重新从环境变量读取)."""
return os.environ.get("MD_VECTOR_API_KEY", "")
def verify_api_key(x_api_key: str | None = Header(None)):