Skip to content

Commit

Permalink
✨ 添加新的配置加载器,支持从YAML、TOML、JSON和环境变量加载配置,并修改默认主机地址
Browse files Browse the repository at this point in the history
  • Loading branch information
snowykami committed Dec 2, 2024
1 parent fd3f627 commit 93c17b6
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
5 changes: 3 additions & 2 deletions config/default.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
nonebot:
host: 127.0.0.1
host: 0.0.0.0
port: 20216
command_start: ["", "/"]
nickname: [ "liteyuki" ]
default_language: zh
driver: ~fastapi+~httpx+~websockets
alconna_use_command_start: true
gotify_token: "empty token"
gotify_token: "empty token"

45 changes: 45 additions & 0 deletions liteyuki/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,48 @@ def load_config_in_default(no_waring: bool = False) -> dict[str, Any]:
)
)
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})"
1 change: 1 addition & 0 deletions liteyuki/session/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ def message_handler_thread(i_chans: Iterable[Chan[Any]]):
for msg in select(*i_chans):
logger.debug(f"Recv from anybot {msg}")
logger.info(f"Recv from anybot {msg}")
pass

0 comments on commit 93c17b6

Please sign in to comment.