config.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. from dataclasses import dataclass
  3. from pathlib import Path
  4. from typing import Optional
  5. @dataclass(frozen=True)
  6. class AppConfig:
  7. secret_key: str
  8. database_path: Path
  9. mysql_host: str
  10. mysql_port: int
  11. mysql_user: str
  12. mysql_password: str
  13. mysql_database: str
  14. gogs_base_url: str
  15. gogs_token: Optional[str]
  16. require_login_to_view_repo: bool
  17. enable_mock_pay: bool
  18. max_preview_bytes: int
  19. # 支付宝中间层 REST API 配置
  20. pay_api_base_url: str
  21. pay_return_url: str
  22. pay_callback_url: str
  23. def load_config() -> AppConfig:
  24. project_root = Path(__file__).resolve().parent.parent
  25. data_dir = project_root / "data"
  26. data_dir.mkdir(parents=True, exist_ok=True)
  27. # 自动加载 .env 文件(仅当环境变量未设置时生效)
  28. env_file = project_root / ".env"
  29. if env_file.exists():
  30. with open(env_file, encoding="utf-8") as f:
  31. for line in f:
  32. line = line.strip()
  33. if not line or line.startswith("#") or "=" not in line:
  34. continue
  35. key, _, val = line.partition("=")
  36. key = key.strip()
  37. val = val.strip()
  38. if key and key not in os.environ:
  39. os.environ[key] = val
  40. return AppConfig(
  41. secret_key=os.environ.get("SECRET_KEY", "dev-secret-key"),
  42. database_path=Path(os.environ.get("DATABASE_PATH", str(data_dir / "app.db"))),
  43. mysql_host=(os.environ.get("MYSQL_HOST") or "").strip(),
  44. mysql_port=int(os.environ.get("MYSQL_PORT", "3306")),
  45. mysql_user=(os.environ.get("MYSQL_USER") or "").strip(),
  46. mysql_password=(os.environ.get("MYSQL_PASSWORD") or "").strip(),
  47. mysql_database=(os.environ.get("MYSQL_DATABASE") or "sourceshare").strip(),
  48. gogs_base_url=os.environ.get("GOGS_BASE_URL", "http://localhost:6066").rstrip("/"),
  49. gogs_token=os.environ.get("GOGS_TOKEN"),
  50. require_login_to_view_repo=os.environ.get("REQUIRE_LOGIN_TO_VIEW_REPO", "1") not in {"0", "false", "False"},
  51. enable_mock_pay=os.environ.get("ENABLE_MOCK_PAY", "1") in {"1", "true", "True"},
  52. max_preview_bytes=int(os.environ.get("MAX_PREVIEW_BYTES", "200000")),
  53. pay_api_base_url=(os.environ.get("PAY_API_BASE_URL") or "https://aigc-api.aitoolcore.com").rstrip("/"),
  54. pay_return_url=(os.environ.get("PAY_RETURN_URL") or "").strip(),
  55. pay_callback_url=(os.environ.get("PAY_CALLBACK_URL") or "").strip(),
  56. )