nex_buddy/server/app/core/config.py

98 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""运行时配置:环境变量 / .env 为唯一来源,代码里不落任何密钥。"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from urllib.parse import urlsplit
from pydantic_settings import BaseSettings, SettingsConfigDict
# server/app/core/config.py -> nex_buddy/
ROOT = Path(__file__).resolve().parents[3]
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=ROOT / ".env",
env_file_encoding="utf-8",
extra="ignore",
case_sensitive=False,
)
app_name: str = "nex_buddy"
app_env: str = "dev"
app_version: str = "0.1.0"
# 运行时资源根目录:媒体、固件、码表等。默认项目根 data/;
# 服务器/容器部署可用 DATA_DIR 指向宿主机挂载点。
data_dir: Path = ROOT / "data"
database_url: str = "postgresql+asyncpg://postgres:sagacity@192.168.124.203:5432/nex_buddy"
redis_url: str = "redis://192.168.124.203:6379/9"
# 和风 Key / Host 只存数据库,由管理端「平台设置」维护,不从 .env 读取。
# 可选:和风请求走指定代理(服务器本身出不了网时用,如 http://10.0.0.2:3128)。
# 留空则跟随 HTTP(S)_PROXY / ALL_PROXY 环境变量——httpx 默认就是这种行为,
# 而容器里继承到的失效代理正是"连不上和风"最常见的原因之一。
qweather_proxy: str = ""
session_ttl_seconds: int = 7 * 24 * 3600
pair_code_ttl_seconds: int = 600
# 设备屏上二维码的 Web 基地址(手机要能访问到)。
# 默认按设备请求的 Host 推导——设备里配的「服务端地址」就是它,同域部署不用配。
# 仅当 Web 与 API 确实不同域时才在这里(.env)覆盖。
web_base_url: str = ""
# 端口:scripts/dev.sh 起后端、vite 起前端都从 .env 读这两个值,
# 改了 FRONTEND_PORT 后,localhost 的 CORS 源会自动跟着换(见 cors_list)
backend_port: int = 8000
frontend_port: int = 5173
# 扫码登录票据有效期:够扫码 + 手机打开,过期就在设备上重开一次
web_login_ttl_seconds: int = 300
pair_claim_window_seconds: int = 120 # 码消费后 2 分钟内必须换 token
weather_cache_seconds: int = 1800
default_city: str = "杭州"
# 默认不配置:Web 与 API 同域(Nginx 反代 / Vite proxy)时浏览器不需要 CORS。
# 只有确实分离部署(如 web.example.com + api.example.com)才设置,
# 逗号分隔,写完整源(协议 + 域名 + 端口),例如:
# CORS_ORIGINS=https://app.example.com
cors_origins: str = ""
@property
def cors_list(self) -> list[str]:
out: list[str] = []
def add(origin: str) -> None:
origin = origin.strip().rstrip("/")
if origin and origin not in out:
out.append(origin)
for raw in self.cors_origins.split(","):
add(raw)
if "*" in out:
return ["*"]
if self.app_env == "dev":
# localhost 的前端源由端口推导,改 FRONTEND_PORT 不用回来改 CORS。
# 手机通过局域网访问 Vite 时走的是同源代理,也不需要额外加 IP。
add(f"http://localhost:{self.frontend_port}")
add(f"http://127.0.0.1:{self.frontend_port}")
# 配了 WEB_BASE_URL(扫码二维码的 Web 地址)时,它的源就是浏览器实际
# 访问 Web 的源;分离部署时自动放行,不必再抄一遍到 CORS_ORIGINS。
if self.web_base_url.strip():
parts = urlsplit(self.web_base_url.strip())
if parts.scheme and parts.netloc:
add(f"{parts.scheme}://{parts.netloc}")
return out
@lru_cache
def get_settings() -> Settings:
return Settings()
settings = get_settings()