unis-oa/backend/app/config.py

658 lines
29 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.

"""配置读取的两层结构:引导项在配置文件里,其余一切在数据库里。
配置从哪来(高的赢):
1. **环境变量** ``OA_*`` —— 容器 / CI 注入密钥用,名字见 ``dbconfig.ITEMS``;
2. **数据库** ``oa_system_setting`` 里的 ``config:*`` 行 —— 界面上改的就是它,
保存后立刻生效,**不用重启服务**(细节见 :mod:`app.dbconfig`);
3. **配置文件** —— 引导配置 + 运行配置的出厂值,按环境分档(下面一节)。**文件里的值
永远不会被写进库**:库里没有这一项时按文件取值,界面上保存过之后才以库为准;
4. 代码默认值 —— 文件缺失或写错时后端照样起得来,只在日志里报错。
只有一部分配置**必须**留在配置文件里:连数据库之前就得知道的 MySQL 地址与账号、
进程监听的端口、签 JWT 的密钥。这几项叫引导配置,改了要重启,界面上只读。
一份代码,多套环境
==================
同一个包要在自己机器上跑、在测试机上跑、在生产上跑,三套库三套密钥。办法是给配置文件
分档,用环境变量 ``OA_ENV`` 说一声现在跑在哪一档:
* 本机开发:什么都不用设,``OA_ENV`` 默认就是 ``dev``,读到的就是测试那一份;
* 换一档:``OA_ENV=prod python run.py``(写全名 ``production`` 也认);
* 目录挪走:``OA_CONFIG_DIR=/etc/unisoa``,密钥就能留在机器上、不进代码目录;
* 只认一个文件:``OA_CONFIG=/path/to/x.toml``,**此时只读它**,分档文件一概不看
(老部署与测试脚本的用法,行为保持不变)。
每一档读两个文件,后面那一份逐段盖在前面那一份上面(深合并:只覆盖写到的键,
没写的沿用):
1. ``config.toml`` —— 各环境公共的基础值(站点信息、Hub 接口路径、上传上限……);
2. ``config.<环境名>.toml`` —— 这一档自己的差异(库地址账号、密钥、演示开关、MinIO)。
于是 ``config.dev.toml`` 就是本地测试用的那一份,``config.prod.toml`` 是生产用的那一份,
互不影响;部署时只要把 ``OA_ENV`` 设成 ``prod``。生产那一份带真实密钥,不进仓库,
在部署机上从 ``config.prod.toml.example`` 复制出来填。
生产档(``prod`` / ``staging`` / ``gray``)启动时还要过一轮**上线体检**:默认的 JWT
密钥、没关的演示数据、空的数据库口令都会在日志里点名,系统设置页与
``GET /api/v1/support/config`` 里也看得到(:func:`warnings`)。
"""
from __future__ import annotations
import json
import logging
import os
import time
from pathlib import Path
logger = logging.getLogger("unisoa.config")
BASE_DIR = Path(__file__).resolve().parent.parent
try: # Python 3.11+ 自带;低版本装 tomli
import tomllib as _tomllib
except ModuleNotFoundError: # pragma: no cover
try:
import tomli as _tomllib # type: ignore[no-redef]
except ModuleNotFoundError:
_tomllib = None # type: ignore[assignment]
#: 已经退役的老配置文件:启动时还在就提醒一句,它们不再被读取
LEGACY_FILES = (".env", "storage.toml")
#: 没设 ``OA_ENV`` 时算哪一档。默认测试档:本机 ``python run.py`` 起来就是开发环境,
#: 要用生产那一份必须显式说一声(``OA_ENV=prod`` 或 ``config.toml`` 里 ``[env] name``),
#: 不会因为漏设而误连生产库
DEFAULT_ENV = "dev"
#: 决定读哪一档配置文件的环境变量,按顺序取第一个有值的
ENV_VARS = ("OA_ENV", "OA_PROFILE")
#: 想改用文件控制档位就写在基础文件 ``config.toml`` 的这里(Docker 里不想传环境变量时用)。
#: 只能写在 ``config.toml``:档位名决定的是"再去读哪个文件",所以它自己必须待在
#: 一个路径不依赖档位的文件里;写在 ``config.<环境名>.toml`` 里会算不出来,直接忽略
ENV_SWITCH_PATH = ("env", "name")
#: 环境名的常见写法归一化:``OA_ENV=production`` 与 ``OA_ENV=prod`` 是同一档
ENV_ALIASES = {
"dev": "dev",
"develop": "dev",
"development": "dev",
"local": "dev",
"test": "test",
"testing": "test",
"uat": "test",
"staging": "staging",
"stage": "staging",
"gray": "gray",
"pre": "pre",
"prod": "prod",
"production": "prod",
"online": "prod",
}
#: 这些档位算"已经上线",启动时要做上线体检
PROD_ENVS = frozenset({"prod", "staging", "gray"})
#: 环境差异文件的命名模板
ENV_FILE_PATTERN = "config.{env}.toml"
#: 出厂内置的开发用密钥与初始口令:出现在生产档里就是忘了改
DEFAULT_JWT_SECRET = "unisoa-dev-secret"
DEFAULT_ADMIN_PASSWORD = "admin123"
#: 一看就是占位的 JWT 密钥(模板与文档里都这么写),生产档出现同样要点名
PLACEHOLDER_JWT_SECRETS = frozenset({DEFAULT_JWT_SECRET, "change-me", "change-me-in-production"})
def _normalize_env(text: str) -> str:
"""环境名归一化:大小写、``production`` / ``prod`` 这类全名都收拢到一个档。"""
cleaned = str(text).strip().strip("'\"").lower()
return ENV_ALIASES.get(cleaned, cleaned) or DEFAULT_ENV
#: 本次启动定下来的(环境名, 这个名字是谁给的),在 :func:`_load_layers` 里算一次
_ENV: tuple[str, str] = (DEFAULT_ENV, f"内置默认档 {DEFAULT_ENV}")
def env_name() -> str:
"""当前环境名(``dev`` / ``prod`` / …),取法见 :func:`env_source`。"""
return _ENV[0]
def env_source() -> str:
"""这一档是谁定的,高的是:
1. 环境变量 ``OA_ENV`` / ``OA_PROFILE`` —— 容器编排与 CI 注入,最明确;
2. 基础文件 ``config.toml`` 的 ``[env] name`` —— 不想传变量时改文件即可;
3. 内置默认档 :data:`DEFAULT_ENV`。
"""
return _ENV[1]
def is_production() -> bool:
"""当前这一档算不算生产(决定要不要做上线体检)。"""
return env_name() in PROD_ENVS
def config_dir() -> Path:
"""分档配置文件所在目录:``OA_CONFIG_DIR`` 指定的路径,否则 ``backend/``。"""
text = os.environ.get("OA_CONFIG_DIR", "").strip()
return Path(text).expanduser() if text else BASE_DIR
def _files_for(env: str, single: str = "") -> list[Path]:
"""按给定档位列出要找的配置文件,**按优先级从低到高**(与 :func:`_load_layers` 同序)。
平时是两个:``config.toml``(公共基础)与 ``config.<环境名>.toml``(本档差异);
设了 ``OA_CONFIG_DIR`` 再各多两个(代码里的低一层、目录里的高一层);
给了 ``single``(``OA_CONFIG``)就只剩它一个 —— 指定单一文件时不再叠加任何分档文件,
老部署与测试脚本传哪个文件就真只用哪个文件。
"""
if single:
return [Path(single).expanduser()]
directories = _search_dirs()
names = ["config.toml", ENV_FILE_PATTERN.format(env=env)]
files: list[Path] = []
for name in names:
for directory in directories:
path = directory / name
if path not in files:
files.append(path)
return files
def config_files() -> list[Path]:
"""本次启动要读的配置文件,**按优先级从低到高**(档位取 :func:`env_name`)。"""
return _files_for(_ENV[0], os.environ.get("OA_CONFIG", "").strip())
def config_path() -> Path:
"""主配置文件:环境文件在就报环境文件,否则报基础文件(日志与状态页用)。"""
files = config_files()
for path in reversed(files):
if path.exists():
return path
return files[-1]
def _read_file(path: Path) -> dict:
"""读一个配置文件;不存在、解析不了都不抛异常,回落到更低一档的值。"""
if _tomllib is None: # pragma: no cover - 取决于解释器版本
logger.error("未找到 tomllib/tomli(需要 Python 3.11+),全部使用默认配置")
return {}
if not path.exists():
logger.info("配置文件 %s 不存在,这一档没有它", path)
return {}
try:
with path.open("rb") as handle:
return _tomllib.load(handle)
except Exception:
logger.exception("配置文件 %s 解析失败,本次忽略它", path)
return {}
def _merge(base: dict, overlay: dict) -> dict:
"""把环境文件叠在基础文件上:同名小节只覆盖写到的键,没写的沿用基础值。"""
merged = dict(base)
for key, value in overlay.items():
current = merged.get(key)
merged[key] = _merge(current, value) if isinstance(current, dict) and isinstance(value, dict) else value
return merged
def _warn_legacy_files() -> None:
"""老 ``.env`` / ``storage.toml`` 还在就提一句,别让人以为它们还在生效。"""
for name in LEGACY_FILES:
if (BASE_DIR / name).exists():
logger.warning(
"检测到旧配置文件 %s,它已不再被读取;引导配置与运行配置的出厂值都在分档配置文件里",
BASE_DIR / name,
)
#: 每一份配置文件的读取结果(含原文,只在本模块内用;对外走 :func:`layers_view`)
_LAYERS: list[dict] = []
def _dig(data: dict, path: tuple[str, ...]):
"""按 ``(section, key, ...)`` 在一份 dict 里往下摸,摸不到回 ``None``。"""
node = data
for part in path:
if not isinstance(node, dict) or part not in node:
return None
node = node[part]
return node
def _pick_env(base_data: dict) -> tuple[str, str]:
"""定档:环境变量 > 基础文件的 ``[env] name`` > 内置默认档,顺手带上"谁给的"。"""
for var in ENV_VARS:
text = os.environ.get(var, "").strip()
if text:
return _normalize_env(text), f"环境变量 {var}={text}"
value = _dig(base_data, ENV_SWITCH_PATH)
if value not in (None, ""):
return _normalize_env(value), f"{(config_dir() / 'config.toml').name} 的 [env] name = {value}"
return DEFAULT_ENV, f"内置默认档 {DEFAULT_ENV}"
def _record(path: Path, purpose: str, data: dict) -> None:
_LAYERS.append({"path": str(path), "purpose": purpose, "exists": path.exists(), "data": data})
def _missing_note() -> None:
logger.warning(
"没读到任何配置文件(%s),全部使用默认配置;模板见 config.toml.example",
"、".join(str(path) for path in config_files()),
)
def _search_dirs() -> list[Path]:
"""配置文件要找的几个目录,**按优先级从低到高**。
平时只有 ``backend/`` 一个。设了 ``OA_CONFIG_DIR``(Docker 挂 ``/etc/unisoa``、
或把配置整目录搬走)就是两个:代码/镜像里带的那份是低一层的基础值,挂载目录里的是
高一层。这样部署机上可以只挂一份两行的 ``config.toml``(只写 ``[env] name``)加一份
``config.<档名>.toml``,不必把整份基础值抄出去,也免得两边各改一半对不上。
"""
directories = [BASE_DIR]
external = config_dir()
if external not in directories:
directories.append(external)
return directories
def _load_layers() -> dict:
"""先定档,再按优先级把各档配置文件叠成一份原文,并记下每一档读到了什么。
定档必须发生在读环境文件之前:档名决定的是"再去读哪个文件",所以它只能来自
环境变量或路径不依赖档名的那些文件(各级 ``config.toml``,或 ``OA_CONFIG`` 指定的那一个)。
"""
global _ENV
single_raw = os.environ.get("OA_CONFIG", "").strip()
if single_raw:
single = Path(single_raw).expanduser()
only = _read_file(single)
_ENV = _pick_env(only)
_record(single, "single", only)
if not only:
_missing_note()
_warn_legacy_files()
return only
# 第一趟:把各级基础值(代码里的 -> 挂载目录里的)叠起来,档位从叠完的结果里定
directories = _search_dirs()
base_data: dict = {}
for index, directory in enumerate(directories):
path = directory / "config.toml"
data = _read_file(path)
_record(path, "base" if index == 0 else "override", data)
base_data = _merge(base_data, data)
_ENV = _pick_env(base_data)
# 第二趟:按定下来的档位读各档差异文件,同样是代码里的低、挂载目录里的高
merged = base_data
overlay_found = False
last = len(directories) - 1
for index, directory in enumerate(directories):
path = directory / ENV_FILE_PATTERN.format(env=_ENV[0])
data = _read_file(path)
_record(path, "env" if index == last else "env_code", data)
if data:
overlay_found = True
if _dig(data, ENV_SWITCH_PATH) not in (None, ""):
logger.warning(
"%s 里的 [env] name 不生效,已忽略:档位决定的是「再去读哪个文件」,"
"只能写在 config.toml 里(或用环境变量 %s)",
path,
" / ".join(ENV_VARS),
)
merged = _merge(merged, data)
if not merged:
_missing_note()
elif not overlay_found:
logger.warning(
"档位 %s 的差异文件一个都没找到(%s),只能靠基础值与默认值跑;生产模板见 config.prod.toml.example",
_ENV[0],
"、".join(str(directory / ENV_FILE_PATTERN.format(env=_ENV[0])) for directory in directories),
)
_warn_legacy_files()
return merged
def layers_view() -> list[dict]:
"""读了哪几份配置文件(给状态页与日志看,不含文件内容)。"""
return [
{
"path": layer["path"],
"purpose": layer["purpose"],
"exists": layer["exists"],
"loaded": bool(layer["data"]),
}
for layer in _LAYERS
]
def layer_of(path: tuple[str, ...]) -> str:
"""某一项的出厂值来自哪一份文件:``base`` / ``env`` / ``single``,都没有就空串。"""
for layer in reversed(_LAYERS):
node = layer["data"]
found = True
for part in path:
if not isinstance(node, dict) or part not in node:
found = False
break
node = node[part]
if found:
return str(layer["purpose"])
return ""
#: 各档配置文件叠好之后的原文。只在启动时读一次,改了文件要重启
RAW: dict = _load_layers()
def file_loaded() -> bool:
"""配置文件读到了没有(一份都没读到也能跑,全用默认值)。"""
return bool(RAW)
def file_value(path: tuple[str, ...]):
"""只查配置文件里的值(不看环境变量、不看库),用于"出厂值"与恢复默认。"""
node = RAW
for part in path:
if not isinstance(node, dict) or part not in node:
return None
node = node[part]
return node
def raw(path: tuple[str, ...], env: str = "", default=None):
"""按 ``(section, key)`` 取**引导项**:环境变量 > 配置文件 > ``default``。
运行配置不走这里(走 :mod:`app.dbconfig`,那里还要多一层"数据库优先"),
这里保留给引导项和老调用点用。
"""
if env:
text = os.environ.get(env)
if text is not None and text.strip() != "":
return text
value = file_value(path)
return default if value is None else value
def env_overrides() -> list[str]:
"""当前真正设了值的环境变量,状态页用它解释"这一项是谁给的"。"""
from . import dbconfig
return dbconfig.env_overrides()
# ---------------------------------------------------------------------------
# 引导配置:连上数据库之前就得知道的东西,改了要重启
# ---------------------------------------------------------------------------
#: 允许后端在启动时**新建**的库名(逗号分隔;结尾 ``*`` 是前缀通配,单独一个 ``*`` = 不设限,
#: 留空 = 一个都不许建)。
#:
#: 为什么要这么一道闸:引导配置默认用 root 连库、``auto_create_schema`` 又开着,于是
#: ``OA_DB_NAME`` 打错一个字,MySQL 上就悄悄多出一个全套表 + 演示数据的库,跑完没人删。
#: 2026-10 那次这么攒出六个来路说不清的临时库(dictkeep / uidemo / ui / prodtest / …)。
#: 库**已经存在**时这道闸不管事——只是连上去,不建库,老部署与「把 ``OA_DB_NAME``
#: 指到一个已同步过组织的库」都不受影响。
#: 默认值只有开发库一个名字——**一个环境一个库**。每个环境在自己的配置里点名自己的库
#: (生产档写 ``unis_oa_prod``),除此之外后端一个库都不许多建。
#: 需要临时库的工具不走这条路径:它们自己 ``CREATE DATABASE``、收尾自己
#: ``DROP DATABASE``,于是共享的 MySQL 上平时只有开发库一个库,只在它们跑着的那会儿
#: 短暂多出一个。
DEFAULT_DB_CREATE_ALLOWLIST = "unis_oa"
#: ``字段名 -> (配置文件路径, 环境变量名, 默认值)``;类型按默认值推断
_BOOTSTRAP: dict[str, tuple[tuple[str, ...], str, object]] = {
"db_host": (("database", "host"), "OA_DB_HOST", "127.0.0.1"),
"db_port": (("database", "port"), "OA_DB_PORT", 3306),
"db_user": (("database", "user"), "OA_DB_USER", "root"),
"db_password": (("database", "password"), "OA_DB_PASSWORD", ""),
"db_name": (("database", "name"), "OA_DB_NAME", "unis_oa"),
"auto_create_schema": (("database", "auto_create_schema"), "OA_AUTO_CREATE_SCHEMA", True),
"db_create_allowlist": (("database", "create_allowlist"), "OA_DB_CREATE_ALLOWLIST",
DEFAULT_DB_CREATE_ALLOWLIST),
"jwt_secret": (("security", "jwt_secret"), "OA_JWT_SECRET", "unisoa-dev-secret"),
"jwt_algorithm": (("security", "jwt_algorithm"), "OA_JWT_ALGORITHM", "HS256"),
"host": (("server", "host"), "OA_HOST", "0.0.0.0"),
"port": (("server", "port"), "OA_PORT", 8000),
"admin_account": (("seed", "admin_account"), "OA_ADMIN_ACCOUNT", "admin"),
"admin_password": (("seed", "admin_password"), "OA_ADMIN_PASSWORD", "admin123"),
"seed_demo": (("seed", "demo_data"), "OA_SEED_DEMO", True),
}
BOOTSTRAP_NAMES = tuple(_BOOTSTRAP)
#: 内置超管的出厂账号名。``[seed] admin_account`` 换成别的名字部署时,
#: 启动迁移(``seed._align_admin_account``)靠它认出老库里那个内置账号并跟着改名。
DEFAULT_ADMIN_ACCOUNT = str(_BOOTSTRAP["admin_account"][2])
def _as_bool(value, default: bool) -> bool:
if isinstance(value, bool):
return value
if value is None:
return default
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _coerce(value, sample):
"""按默认值的类型洗一下引导项(环境变量给的永远是字符串)。"""
if isinstance(sample, bool):
return _as_bool(value, sample)
if isinstance(sample, int) and not isinstance(sample, bool):
try:
return int(str(value).strip())
except (TypeError, ValueError):
return sample
if isinstance(sample, (list, tuple)):
text = str(value)
return tuple(part.strip() for part in text.replace(",", ",").split(",") if part.strip())
return str(value).strip() if value is not None else sample
def bootstrap_value(name: str, default=None):
"""取一个引导配置项:环境变量 > 配置文件 > ``default``。"""
spec = _BOOTSTRAP.get(name)
if spec is None:
return default
path, env, fallback = spec
return _coerce(raw(path, env, default if default is not None else fallback), fallback)
def bootstrap_explicit(name: str):
"""引导配置里"真的写了值"才回值(环境变量 > 配置文件),没写回 ``None``。
跟 :func:`bootstrap_value` 的区别是它不拿默认值冒充"你配置的",
用来判断某一项到底归谁管 —— 内置超管的账号名就靠它区分
"配置文件点名要改名" 与 "配置文件根本不管这件事"。
"""
spec = _BOOTSTRAP.get(name)
if spec is None:
return None
path, env, _fallback = spec
text = os.environ.get(env) if env else None
if text is not None and text.strip():
return text.strip()
value = file_value(path)
return None if value is None else value
#: 库里记着"内置超管现在用哪个登录账号"的那一行(``seed._align_admin_account`` 维护)
ADMIN_ACCOUNT_KEY = "system.admin_account"
#: 上一条的读取结果缓存:``(monotonic 时刻, 账号名)``,TTL 跟运行配置快照一致
_admin_account_cache: tuple[float, str] = (0.0, "")
def forget_admin_account_cache() -> None:
"""让内置超管账号名的缓存作废(启动改名之后立刻要读到新名字)。"""
global _admin_account_cache
_admin_account_cache = (0.0, "")
def _admin_account_from_db() -> str:
"""读库里记着的内置超管账号名;库不通或还没记过就回空串。"""
from . import models
from .db import SessionLocal
try:
with SessionLocal() as db:
row = db.get(models.SystemSetting, ADMIN_ACCOUNT_KEY)
except Exception: # pragma: no cover - 库还没起来时配置文件照样能把服务带起来
return ""
value = getattr(row, "value", None)
if isinstance(value, str):
try:
value = json.loads(value or "{}")
except ValueError:
return ""
return str((value or {}).get("account") or "").strip()
def admin_account_name() -> str:
"""内置超管(唯一的本地管理员,也是唯一走本地口令登录的账号)的登录账号。
口径是 **显式配置 > 数据库记录 > 出厂默认值**:账号建号之后它就是库里的一行,
配置文件不需要再写 ``[seed] admin_account``;只有要把账号名改名
(例如把 ``admin`` 腾给统一身份同步进来的人)时才在配置文件或环境变量里点名,
启动时 ``seed._align_admin_account`` 会连着身份 DN 与审批引用一起搬走。
"""
explicit = bootstrap_explicit("admin_account")
if explicit:
return str(explicit).strip()
global _admin_account_cache
recorded = ""
now = time.monotonic()
try:
from . import dbconfig
if _admin_account_cache[1] and now - _admin_account_cache[0] < dbconfig.cache_seconds():
return _admin_account_cache[1]
recorded = _admin_account_from_db()
except Exception: # pragma: no cover - 只看配置文件不起库的场景(分档自检脚本、库还没建)
return DEFAULT_ADMIN_ACCOUNT
if recorded:
_admin_account_cache = (now, recorded)
return recorded
return DEFAULT_ADMIN_ACCOUNT
def bootstrap_view() -> dict:
"""全部引导项的生效值。口令与密钥只回"配了没有",永不外泄。"""
values = {name: bootstrap_value(name) for name in _BOOTSTRAP}
# 内置超管账号名以数据库记录为准(配置文件没写时 bootstrap_value 只能给出厂默认值)
values["admin_account"] = admin_account_name()
flags = {
"db_password_set": bool(values.get("db_password")),
"admin_password_set": bool(values.get("admin_password")),
"jwt_secret_set": bool(values.get("jwt_secret")),
}
for secret in ("db_password", "admin_password", "jwt_secret"):
values.pop(secret, None)
values.update(flags)
values["env"] = env_name()
values["env_source"] = env_source()
values["layers"] = layers_view()
values["warnings"] = warnings()
return values
def warnings() -> list[str]:
"""上线体检:生产档里那些一看就是开发值的引导配置,启动就在日志里点名。
只提醒、不拦启动 —— 拦死了就没法先把服务起来看日志了。开发档一律回空表,
免得本机天天被念。这里只看配置文件与环境变量,不看库:这 13 项本来也不进库。
**提醒文本里绝不出现口令与密钥本身**,连"出厂默认值是多少"都不写:这几条会进日志、
也会随 ``GET /api/v1/system/info`` 回到界面上,跟"密钥只进不出"是同一条规矩。
"""
if not is_production():
return []
env_file = ENV_FILE_PATTERN.format(env=env_name())
hint = f"请在 {env_file} 里改掉,或用环境变量注入(引导配置,界面上改不了,改完重启)"
out: list[str] = []
secret = str(bootstrap_value("jwt_secret") or "").strip()
if not secret:
out.append(f"【{env_name()}】JWT 签名密钥是空的:{hint}(OA_JWT_SECRET)")
elif secret in PLACEHOLDER_JWT_SECRETS:
out.append(f"【{env_name()}】JWT 签名密钥还是出厂模板里的占位值:{hint}(OA_JWT_SECRET)")
if _as_bool(bootstrap_value("seed_demo"), True):
out.append(
f"【{env_name()}】还在种演示数据([seed] demo_data):上线请改成 false,"
"或用 OA_SEED_DEMO=false(已经种进去的演示数据不会自动清理)"
)
if not str(bootstrap_value("db_password") or "").strip():
out.append(f"【{env_name()}】MySQL 账号 {bootstrap_value('db_user')} 没设口令:{hint}(OA_DB_PASSWORD)")
admin_password = str(bootstrap_value("admin_password") or "")
if not admin_password.strip():
out.append(
f"【{env_name()}】内置超管 {bootstrap_value('admin_account')} 的初始口令是空的:"
f"{hint}(OA_ADMIN_PASSWORD)"
)
elif admin_password == DEFAULT_ADMIN_PASSWORD:
out.append(
f"【{env_name()}】内置超管 {bootstrap_value('admin_account')} 的初始口令还是出厂默认值:"
f"{hint}(OA_ADMIN_PASSWORD),或首次登录后改密"
)
return out
class Settings:
"""``settings.<字段>`` 的统一入口:引导项走文件/环境变量,其余问数据库。
历史调用点写的都是 ``settings.site_name`` / ``settings.hub_base_url``,这个
类把 ``__getattr__`` 接给 :mod:`app.dbconfig`,于是同样的写法读到的就是
**当前生效值**:界面上刚保存的 Hub 地址、站点名、上传上限,下一行代码就拿到
新的,不需要重启进程。字段清单见 ``dbconfig.ITEMS`` 与 ``_BOOTSTRAP``。
"""
# --- 引导项:改了要重启 -------------------------------------------------
#: 当前环境名(``OA_ENV``),本机默认 ``dev``
env = property(lambda self: env_name())
#: 主配置文件:环境文件在就是它,否则是基础文件
config_file = property(lambda self: str(config_path()))
#: 本次实际读了哪几份配置文件
config_layers = property(lambda self: layers_view())
config_loaded = property(lambda self: file_loaded())
#: 上线体检结果(只有生产档才有)
config_warnings = property(lambda self: warnings())
db_host = property(lambda self: bootstrap_value("db_host"))
db_port = property(lambda self: bootstrap_value("db_port"))
db_user = property(lambda self: bootstrap_value("db_user"))
db_password = property(lambda self: bootstrap_value("db_password"))
db_name = property(lambda self: bootstrap_value("db_name"))
auto_create_schema = property(lambda self: bootstrap_value("auto_create_schema"))
#: 允许新建的库名白名单(原样字符串,拆分成模式的事交给 ``db.create_allowlist()``)
db_create_allowlist = property(lambda self: bootstrap_value("db_create_allowlist"))
jwt_secret = property(lambda self: bootstrap_value("jwt_secret"))
jwt_algorithm = property(lambda self: bootstrap_value("jwt_algorithm"))
host = property(lambda self: bootstrap_value("host"))
port = property(lambda self: bootstrap_value("port"))
admin_account = property(lambda self: admin_account_name())
admin_password = property(lambda self: bootstrap_value("admin_password"))
seed_demo = property(lambda self: bootstrap_value("seed_demo"))
@property
def database_url(self) -> str:
return (
f"mysql+pymysql://{self.db_user}:{self.db_password}"
f"@{self.db_host}:{self.db_port}/{self.db_name}?charset=utf8mb4"
)
@property
def server_url(self) -> str:
return f"mysql+pymysql://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/?charset=utf8mb4"
def __getattr__(self, name: str):
# 运行配置一律现问 dbconfig(数据库 > 环境变量 > 配置文件 > 默认值)。
from . import dbconfig
if name in dbconfig.BY_NAME:
return dbconfig.value(name)
raise AttributeError(f"没有名为 {name!r} 的配置项")
#: 全局配置入口。它是"活"的:每次属性访问都取当前生效值
settings = Settings()