添加新的配置加载器,支持从YAML、TOML、JSON和环境变量加载配置,并修改默认主机地址
Some checks failed
Docker Image Build / build (push) Failing after 1m25s
Deploy VitePress site to Pages / build (push) Failing after 1m50s

This commit is contained in:
远野千束(神羽) 2024-12-02 21:46:29 +08:00
parent fd3f6272f1
commit 93c17b6026
3 changed files with 49 additions and 2 deletions

View File

@ -1,5 +1,5 @@
nonebot: nonebot:
host: 127.0.0.1 host: 0.0.0.0
port: 20216 port: 20216
command_start: ["", "/"] command_start: ["", "/"]
nickname: [ "liteyuki" ] nickname: [ "liteyuki" ]
@ -7,3 +7,4 @@ nonebot:
driver: ~fastapi+~httpx+~websockets driver: ~fastapi+~httpx+~websockets
alconna_use_command_start: true alconna_use_command_start: true
gotify_token: "empty token" gotify_token: "empty token"

View File

@ -132,3 +132,48 @@ def load_config_in_default(no_waring: bool = False) -> dict[str, Any]:
) )
) )
return config return config
# new config loader
class Loader:
def __init__(self):
self.config = {}
def load_from_yaml(self, fp: str) -> "Loader":
"""从yaml文件加载配置
Args:
fp
"""
with open(fp, 'r') as file:
self.config.update(yaml.safe_load(file))
return self
def load_from_toml(self, fp: str) -> "Loader":
"""从toml文件加载配置"""
with open(fp, 'r') as file:
self.config.update(toml.load(file))
return self
def load_from_json(self, fp: str) -> "Loader":
"""从json文件加载配置"""
with open(fp, 'r') as file:
self.config.update(json.load(file))
return self
def load_from_env(self, prefix: str = "") -> "Loader":
"""从环境变量加载配置"""
for key, value in os.environ.items():
if key.startswith(prefix):
self.config[key[len(prefix):]] = value
return self
def merge(self, loader: "Loader") -> "Loader":
"""合并两个Loader键值对树"""
self.config.update(loader.config)
return self
def get(self, key: str, default: Any = None) -> Any:
"""获取配置值"""
return self.config.get(key, default)
def __repr__(self) -> str:
return f"Loader(config={self.config})"

View File

@ -21,3 +21,4 @@ def message_handler_thread(i_chans: Iterable[Chan[Any]]):
for msg in select(*i_chans): for msg in select(*i_chans):
logger.debug(f"Recv from anybot {msg}") logger.debug(f"Recv from anybot {msg}")
logger.info(f"Recv from anybot {msg}") logger.info(f"Recv from anybot {msg}")
pass