From b29d35acc5db7b08ef8994d9050f975c282a158a Mon Sep 17 00:00:00 2001 From: SilianZ Date: Sun, 10 Mar 2024 01:48:21 +0800 Subject: [PATCH 1/5] =?UTF-8?q?:art:=20=E9=87=8D=E6=9E=84=E9=83=A8?= =?UTF-8?q?=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增使用 `loguru` 编写的 logger - 新增使用 `tqdm` 编写的进度条 - 重构 `config.py` - 修正了多处工地英语 - 将 `print` 改为 `logger` - 更新 README 以适应新的 config 文件 - 修改 `requirements.txt` - 修改 Dashboard 的部分样式 - 更新 config.*.example - 更新配置文件语言至 YAML - 更新 `Dockerfile` 以适配新的版本 - 更新 `.gitignore` --- .gitignore | 8 +- Dockerfile | 4 +- README.md | 10 +-- config/config.properties.example | 8 -- config/config.yaml.example | 8 ++ container/bmclapi_dashboard/index.html | 2 +- .../bmclapi_dashboard/static/js/index.js | 6 +- container/cluster.py | 32 ++++--- container/config.py | 82 +++++++----------- container/logger.py | 4 + container/timer.py | 5 +- container/web.py | 11 +-- main.py | 1 + requirements.txt | Bin 530 -> 902 bytes 14 files changed, 86 insertions(+), 95 deletions(-) delete mode 100644 config/config.properties.example create mode 100644 config/config.yaml.example create mode 100644 container/logger.py diff --git a/.gitignore b/.gitignore index d01d225..425962e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -<<<<<<< HEAD container/.ssl/ container/bmclapi/ container/cache/ @@ -6,8 +5,11 @@ container/config/ container/__pycache__/ .vscode/ .lh/ -======= config/config.properties __pycache__ .venv ->>>>>>> 1821e9a699e53437109088d3d8cf4bb4a1bf9a50 +logs +config/config.yaml +bmclapi +bmclapi_dashboard +cache \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 7424901..5599876 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ WORKDIR /python-openbmclapi ADD . . RUN pip install -r requirements.txt --no-deps -VOLUME /python-openbmclapi/cache -ENV web_port=8080 +VOLUME /python-openbmclapi/bmclapi +ENV web_port=8800 EXPOSE $web_port CMD ["python", "./container/main.py"] diff --git a/README.md b/README.md index f7dfd8c..65809ca 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ python ./container/main.py ``` -4. 在 `config.properties` 中,填写你的 `cluster.id`(即 `CLUSTER_ID`)和 `cluster.secret`(即 `CLUSTER_SECRET`)。 +4. 在 `config.yaml` 中,填写你的 `cluster_id`(即 `CLUSTER_ID`)和 `cluster_secret`(即 `CLUSTER_SECRET`)。 5. 重新启动程序。 @@ -69,8 +69,8 @@ ```sh docker run -d \ - -v ${/data/python-openbmclapi}:/python-openbmclapi/container/cache \ - -v ${/path/to/your/config}:/python-openbmclapi/config/config.properties \ + -v ${/data/python-openbmclapi}:/python-openbmclapi/bmclapi \ + -v ${/path/to/your/config}:/python-openbmclapi/config/config.yaml \ -p ${web.port}:${web.port} \ --restart always \ --name python-openbmclapi \ @@ -81,9 +81,9 @@ `web.port` - 对外开放的端口。 - `/path/to/your/config` - 配置文件(你需要从此仓库中下载 `config/config.properties.example` 并重命名为 `config.properties` 来进行配置)的存放路径。 + `/path/to/your/config` - 配置文件(你需要从此仓库中下载 `config/config.yaml.example` 并重命名为 `config.yaml` 来进行配置)的存放路径。 - `/data/python-openbmclapi` - `cache` 文件夹挂载的路径。 + `/data/python-openbmclapi` - `bmclapi` 文件夹(即缓存 `cache` 文件夹)挂载的路径。 # 鸣谢 diff --git a/config/config.properties.example b/config/config.properties.example deleted file mode 100644 index 935bfda..0000000 --- a/config/config.properties.example +++ /dev/null @@ -1,8 +0,0 @@ -cluster.id= -cluster.secret= -download.threads=64 -web.host= -web.port=8800 -web.publicport=8800 -web.skipsign=True -web.ssl= diff --git a/config/config.yaml.example b/config/config.yaml.example new file mode 100644 index 0000000..292d713 --- /dev/null +++ b/config/config.yaml.example @@ -0,0 +1,8 @@ +byoc: '' +cluster_id: '' +cluster_secret: '' +download_threads: 64 +timeout: 30 +web_host: '' +web_port: 8800 +web_publicport: 8800 diff --git a/container/bmclapi_dashboard/index.html b/container/bmclapi_dashboard/index.html index fb763a9..e8d1bb3 100644 --- a/container/bmclapi_dashboard/index.html +++ b/container/bmclapi_dashboard/index.html @@ -5,7 +5,7 @@ - OPENBMCLAPI - TTB Network + Python OpenBMCLAPI Dashboard diff --git a/container/bmclapi_dashboard/static/js/index.js b/container/bmclapi_dashboard/static/js/index.js index 0b2d8e6..51360fb 100644 --- a/container/bmclapi_dashboard/static/js/index.js +++ b/container/bmclapi_dashboard/static/js/index.js @@ -77,6 +77,7 @@ const calc_more_bytes = (...values) => { ".container .vcmp-status-bar:hover":"color: #8dcffc;", ".container .vcmp-status-online":"width: 12px;height: 12px;border-radius: 50%;background-color: #0FC6C2;margin: 8px;", ".container .vcmp-status-offline":"width: 12px;height: 12px;border-radius: 50%;background-color: rgba(0, 0, 0, 0.5);margin: 8px;margin-right: 0;", + "h1, h2, h3":"font-family: Microsoft Yahei UI" } set_styles(default_styles) Extendi18nSets("zh_cn", { @@ -260,10 +261,7 @@ const calc_more_bytes = (...values) => { ExtendFlex().append( ExtendFlex().css("domain", "extend-flex-auto").append( ExtendElement("span").append( - ExtendElement("h2").text("Python OpenBMCLAPI Dashboard").valueOf(), - ExtendElement("span").text("Built by ").append( - ExtendElement("a").text("TTB Network").setAttr("href", "https://github.com/TTB-Network/python-openbmclapi/").valueOf() - ).id("dashboard-geo").valueOf() + ExtendElement("h3").text("Python OpenBMCLAPI Dashboard").valueOf(), ).valueOf(), ).valueOf(), ).css("header-bar").valueOf(), diff --git a/container/cluster.py b/container/cluster.py index 1d1a1d4..0982f33 100644 --- a/container/cluster.py +++ b/container/cluster.py @@ -17,6 +17,9 @@ import utils import stats import web +from logger import logger +from tqdm import tqdm +import time PY_VERSION = "1.0.0" VERSION = "1.9.7" @@ -59,7 +62,7 @@ async def fetchToken(self): Timer.delay(self.fetchToken, delay=float(content['ttl']) / 1000.0 - 600) except aiohttp.ClientError as e: - print(f"Error fetching token: {e}") + logger.error(f"Error fetching token: {e}.") async def getToken(self) -> str: if not self.token: await self.fetchToken() @@ -119,12 +122,14 @@ async def download(self, session: aiohttp.ClientSession): self.download_bytes.add(-size) await self.files.put(file) async def check_file(self): - print("Requesting files...") + logger.info("Requesting filelist...") filelist = await self.get_file_list() filesize = sum((file.size for file in filelist)) total = len(filelist) byte = 0 miss = [] + pbar = tqdm(total=total, unit=' file(s)', unit_scale=True) + pbar.set_description("Checking files") for i, file in enumerate(filelist): filepath = Path(str(self.dir) + f"/{file.hash[:2]}/{file.hash}") if not filepath.exists() or filepath.stat().st_size != file.size: @@ -133,15 +138,15 @@ async def check_file(self): await asyncio.sleep(0) b = utils.calc_more_bytes(byte, filesize) byte += file.size - print(f"<<>>Check file {i}/{total} ({b[0]}/{b[1]})") + pbar.update(1) if not miss: - print(f"<<>>Checked all files!") + logger.info("Checked all files!") await self.start_service() return filelist = miss filesize = sum((file.size for file in filelist)) total = len(filelist) - print(f"<<>>Missing files: {total}({utils.calc_bytes(filesize)})") + logger.info(f"Missing files: {total}({utils.calc_bytes(filesize)}).") for file in filelist: await self.files.put(file) self.download_bytes = utils.Progress(5, filesize) @@ -153,14 +158,17 @@ async def check_file(self): "User-Agent": UA, "Authorization": f"Bearer {await token.getToken()}" }), ))) + pbar = tqdm(total=total, unit=' file(s)', unit_scale=True) + pre = 0 while any([not timer.called for timer in timers]): b = utils.calc_more_bytes(self.download_bytes.get_cur(), filesize) bits = self.download_bytes.get_cur_speeds() or [0] minbit = min(bits) bit = utils.calc_more_bit(minbit, bits[-1], max(bits)) - eta = self.download_bytes.get_eta() - print(f"<<>>Downloading files... {self.download_files.get_cur()}/{total} {b[0]}/{b[1]}, eta: {utils.format_time(eta if eta != -1 else None)}, total: {utils.format_time(self.download_bytes.get_total())}, Min: {bit[0]}, Cur: {bit[2]}, Max: {bit[1]}, Files: {self.download_files.get_cur_speed()}/s") + pbar.set_description(f"Downloading files | Curent speed: {bit[2]}") await asyncio.sleep(1) + pbar.update(self.download_files.get_cur() - pre) + pre = self.download_files.get_cur() await self.start_service() async def start_service(self): tokens = await token.getToken() @@ -182,11 +190,11 @@ async def enable(self): if not web.get_ssl() and not (Path(".ssl/cert.pem").exists() and Path(".ssl/key.pem").exists()): await self.emit("request-cert") self.cur_counter = stats.Counters() - print("Connected Main Server.") + logger.info("Connected to the Main Server.") async def message(self, type, data): if type == "request-cert": cert = data[1] - print("Requested cert!") + logger.info("Requested cert!") cert_file = Path(".ssl/cert.pem") key_file = Path(".ssl/key.pem") for file in (cert_file, key_file): @@ -203,9 +211,9 @@ async def message(self, type, data): self.keepalive.block() self.keepalive = Timer.delay(self.keepaliveTimer, (), 5) if len(data) == 2 and data[1] == True: - print("Checked! Can service") + logger.info("Checked! Starting the service") return - print("Error:" + data[0]['message']) + logger.error("Error:" + data[0]['message']) Timer.delay(self.enable) elif type == "keep-alive": COUNTER.hit -= self.cur_counter.hit @@ -231,7 +239,7 @@ async def get_file_list(self): "cache": "" }) as req: req.raise_for_status() - print("Requested files") + logger.info("Requested filelist.") parser = avro_io.DatumReader(schema.parse( ''' diff --git a/container/config.py b/container/config.py index f8e1096..fa9ce47 100644 --- a/container/config.py +++ b/container/config.py @@ -1,62 +1,38 @@ from pathlib import Path +import yaml +class CFG: + def __init__(self, path: str) -> None: + self.file = Path(path) + self.cfg = {} + if self.file.exists(): + self.load() -class Property: - def __init__(self, config: str, exists_ok: bool = True) -> None: - self.file = Path(config) - self.properties = {} - if self.file.exists(): - self.parse_file() - self.exists_ok = exists_ok - - def parse_file(self): - with open(self.file, "r", encoding="utf-8") as f: - for line in f.readlines(): - line = line.strip() - if not line or line.startswith('#'): - continue - key, value = line.split('=', 1) - value = value.strip('"') - self.properties[key] = value - def set(self, key, value): - self.properties[key] = str(value) + def load(self): + with open(self.file, 'r', encoding="utf-8") as f: + self.cfg = yaml.load(f.read(), Loader=yaml.FullLoader) - def get(self, key, default=None): - val = self.properties.get(key, None) - if not self.exists_ok and val is None: - self.set(key, default or "") - self.save() - return val or str(default) - def getBoolean(self, key, def_: bool = False): - val = self.get(key, def_) - return val.lower() in ("true", "1", "t", "yes", "y") - def getInteger(self, key, def_: int = 0): - val = self.get(key, def_) - return int(val) if val.isnumeric() else def_ - def __getitem__(self, key): - return self.properties.get(key) - def __setitem__(self, key, value): - self.set(key, value) - - def save(self): - sorted_dict = sorted(self.properties.items()) - self.file.parent.mkdir(exist_ok=True, parents=True) - with open(self.file, 'w', encoding="utf-8") as file: - for key, value in sorted_dict: - if "\n" in value: - value = f'"{value}"' - file.write(f"{key}={value}\n") + def get(self, key, default): + value = self.cfg.get(key, None) + if value is None: + self.write(key, default) + return value -Config: Property = Property("./config/config.properties", False) + def write(self, key, value): + self.cfg[key] = value + with open(self.file, 'w', encoding="utf-8") as f: + yaml.dump(data=self.cfg, stream=f, allow_unicode=True) -CLUSTER_ID = Config.get("cluster.id", None) or "" -CLUSTER_SECRET = Config.get("cluster.secret", None) or "" -MAX_DOWNLOAD = Config.getInteger("download.threads", 64) -PORT = Config.getInteger("web.port", 8800) -PUBLICPORT = Config.getInteger("web.publicport", 8800) -PUBLICHOST = Config.get("web.host", "") -BYOC = False -TIMEOUT = 30 +Config = CFG("./config/config.yaml") + +CLUSTER_ID = Config.get("cluster_id", "") +CLUSTER_SECRET = Config.get("cluster_secret", "") +MAX_DOWNLOAD = Config.get("download_threads", 64) +PORT = Config.get("web_port", 8800) +PUBLICPORT = Config.get("web_publicport", 8800) +PUBLICHOST = Config.get("web_host", "") +BYOC = Config.get("byoc", False) +TIMEOUT = Config.get("timeout", 30) MIN_RATE_TIMESTAMP = 1000 MIN_RATE = 500 REQUEST_BUFFER = 1024 * 8 diff --git a/container/logger.py b/container/logger.py new file mode 100644 index 0000000..6113c76 --- /dev/null +++ b/container/logger.py @@ -0,0 +1,4 @@ +from loguru import logger +from pathlib import Path + +logger.add(Path("./logs/{time}.log"), rotation="3 hours") diff --git a/container/timer.py b/container/timer.py index 094b220..4928060 100644 --- a/container/timer.py +++ b/container/timer.py @@ -2,6 +2,7 @@ import inspect import time import traceback +from logger import logger class Task: @@ -44,7 +45,7 @@ def block(self): self.blocked = True async def callback_error(self): if not self.error: - print(traceback.format_exc()) + logger.debug(traceback.format_exc()) return try: if inspect.iscoroutinefunction(self.error): @@ -52,7 +53,7 @@ async def callback_error(self): else: self.error() except: - print(traceback.format_exc()) + logger.debug(traceback.format_exc()) class TimerManager: def delay(self, target, args = (), delay: float = 0, callback = None): task = Task(target=target, args=args, delay=delay, back=callback) diff --git a/container/web.py b/container/web.py index 7b94975..e227d78 100644 --- a/container/web.py +++ b/container/web.py @@ -19,6 +19,7 @@ import config import filetype import urllib.parse as urlparse +from logger import logger class Route: @@ -195,7 +196,7 @@ async def handle(self, request: 'Request', client: Client): }))(request, client) def mount(self, router: Router): self._routes.append(router) - print(f"Serve router at: {router.prefix}") + logger.info(f"Serve router at: {router.prefix}") def mount_resource(self, resource: Resource): self._resources.append(resource) @@ -491,7 +492,7 @@ async def handle(data, client: Client): request: Request = Request(data, client) await app.handle(request, client) await request.skip() - print(request.get_request_time(), "|", request.method.ljust(6), request.get_status_code(), "|", request.get_ip().ljust(16), "|", request.url, request.get_user_agent()) + logger.info(request.method.ljust(6), request.get_status_code(), "|", request.get_ip().ljust(16), "|", request.url, request.get_user_agent()) except TimeoutError: ... except: @@ -542,15 +543,15 @@ async def main(): load_cert() import cluster await cluster.init() - while 1: + while True: try: server = await asyncio.start_server(_handle, host='0.0.0.0', port=config.PORT, ssl=cert) - print(f"Server listen on {config.PORT}{' with ssl' if cert else ''}!") + logger.info(f"Server listening on {config.PORT}{' with ssl' if cert else ''}!") await server.serve_forever() except: if server: server.close() - traceback.print_exc() + logger.error(traceback.format_exc()) @app.get("/favicon.ico") async def _(): diff --git a/main.py b/main.py index c9fb98c..19421de 100644 --- a/main.py +++ b/main.py @@ -5,6 +5,7 @@ from typing import Optional import sys import time +from container.logger import logger from watchdog.observers import Observer from watchdog.events import FileSystemEvent, FileSystemEventHandler encoding = sys.getdefaultencoding() diff --git a/requirements.txt b/requirements.txt index dc2f0dd1cb45cb8122c5459428a3eb87ef3b8adf..bfa65860a062b5efdee2846b46a5c4dc13a2bb3c 100644 GIT binary patch literal 902 zcmZvaO;5sL5QO(^;!i1|d>IcOxNG9oqZIjwZNXA(;K!@a?9vvaY2KHFot>GTcfY@0 zZEHJQap(4C2YcWf+1Li$1554JZY(extNHehQ2m}WzN#PKSX&7?cTDQ_oq}AY*`t=AeS%{Hu0&Z*g-UJ6J#wA}9+sR8oa#}L+n6MyH|JEiEI2J@0%GP2 zZ4xzFdlG3?lty@6xzjVX60R*1g_gXCCzLk)rX7FkmFSm4r6guK3thQd+Y#<#*L6oV z<|_C%N9Xr+GwPaf>ds3X39*7Z>)ulJNHf&0GfaGjH9hLp9>|ks(A)lpKY+>X{h}23 zX{QjAKa<>x&F#q^ov(EnRq3BSvt>7D$^_EXu2uNRc;m=j`6z|x)rJ+kiZ(T|hI;{1 z@2Gt%%^dD)`ylPY+2W1mCNgcvsdlZUXW!1=cQ>BQ7<__`($!wcL%$b#_0Vd-?0q-t UOOmSfdvijs!h7pd8BcuXALzw@^8f$< delta 44 zcmZo;pTsiZ!ek*vkI5yBVv|=e`b{olvYKqfB*baJpvPbY#D Date: Sun, 10 Mar 2024 02:01:37 +0800 Subject: [PATCH 2/5] =?UTF-8?q?:sparkles:=20=E6=9B=B4=E6=96=B0=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 65809ca..daed718 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,9 @@ 🎉 __*新增功能!*__基于 Echart 的 OpenBMCLAPI 仪表盘(Dashboard)。 +🎉 __*新增功能!*__基于 loguru 的**日志器**。 + + # 简介 From 6e6985b0ac7d3423b8f58e892000cf56376a3dff Mon Sep 17 00:00:00 2001 From: SilianZ Date: Sun, 10 Mar 2024 02:18:00 +0800 Subject: [PATCH 3/5] =?UTF-8?q?:bug:=20=E4=BF=AE=E5=A4=8D=E6=BC=8F?= =?UTF-8?q?=E6=B4=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- container/cluster.py | 2 -- container/config.py | 2 +- container/web.py | 2 +- main.py | 1 - 4 files changed, 2 insertions(+), 5 deletions(-) diff --git a/container/cluster.py b/container/cluster.py index 1afeb3b..b79ea7f 100644 --- a/container/cluster.py +++ b/container/cluster.py @@ -1,6 +1,5 @@ import asyncio from dataclasses import dataclass -import glob import hashlib import hmac import io @@ -20,7 +19,6 @@ import web from logger import logger from tqdm import tqdm -import time PY_VERSION = "1.0.0" VERSION = "1.9.7" diff --git a/container/config.py b/container/config.py index fa9ce47..a68e685 100644 --- a/container/config.py +++ b/container/config.py @@ -23,7 +23,7 @@ def write(self, key, value): with open(self.file, 'w', encoding="utf-8") as f: yaml.dump(data=self.cfg, stream=f, allow_unicode=True) -Config = CFG("./config/config.yaml") +Config: CFG = CFG("./config/config.yaml") CLUSTER_ID = Config.get("cluster_id", "") CLUSTER_SECRET = Config.get("cluster_secret", "") diff --git a/container/web.py b/container/web.py index 4a9f146..55817d1 100644 --- a/container/web.py +++ b/container/web.py @@ -493,7 +493,7 @@ async def handle(data, client: Client): async for resp in app.handle(request): await resp(request, client) await request.skip() - logger.info(request.method.ljust(6), request.get_status_code(), "|", request.get_ip().ljust(16), "|", request.url, request.get_user_agent()) + logger.info(request.get_request_time(), "|", request.method.ljust(6), request.get_status_code(), "|", request.get_ip().ljust(16), "|", request.url, request.get_user_agent()) except TimeoutError: ... except: diff --git a/main.py b/main.py index 19421de..c9fb98c 100644 --- a/main.py +++ b/main.py @@ -5,7 +5,6 @@ from typing import Optional import sys import time -from container.logger import logger from watchdog.observers import Observer from watchdog.events import FileSystemEvent, FileSystemEventHandler encoding = sys.getdefaultencoding() From e9c6a3f777a508b987a31f6090c76c4cdc6b6ed6 Mon Sep 17 00:00:00 2001 From: SilianZ Date: Sun, 10 Mar 2024 02:34:54 +0800 Subject: [PATCH 4/5] =?UTF-8?q?:bug:=20=E4=BF=AE=E5=A4=8D=E6=BC=8F?= =?UTF-8?q?=E6=B4=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 14 ++++++++++++++ config/config.yaml.example | 2 +- container/config.py | 16 ++++++++-------- container/web.py | 2 +- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index daed718..1e77eca 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,20 @@ `/data/python-openbmclapi` - `bmclapi` 文件夹(即缓存 `cache` 文件夹)挂载的路径。 +# 配置文件 + +```yaml +byoc: '' +cluster_id: '' +cluster_secret: '' +download_threads: 64 +timeout: 30 +web_host: '' +web_port: 8800 +web_publicport: 8800 + +``` + # 鸣谢 [LiterMC/go-openbmclapi](https://github.com/LiterMC/go-openbmclapi) diff --git a/config/config.yaml.example b/config/config.yaml.example index 292d713..9e294be 100644 --- a/config/config.yaml.example +++ b/config/config.yaml.example @@ -1,4 +1,4 @@ -byoc: '' +byoc: false cluster_id: '' cluster_secret: '' download_threads: 64 diff --git a/container/config.py b/container/config.py index a68e685..4d91069 100644 --- a/container/config.py +++ b/container/config.py @@ -25,14 +25,14 @@ def write(self, key, value): Config: CFG = CFG("./config/config.yaml") -CLUSTER_ID = Config.get("cluster_id", "") -CLUSTER_SECRET = Config.get("cluster_secret", "") -MAX_DOWNLOAD = Config.get("download_threads", 64) -PORT = Config.get("web_port", 8800) -PUBLICPORT = Config.get("web_publicport", 8800) -PUBLICHOST = Config.get("web_host", "") -BYOC = Config.get("byoc", False) -TIMEOUT = Config.get("timeout", 30) +CLUSTER_ID: str = Config.get("cluster_id", "") +CLUSTER_SECRET: str = Config.get("cluster_secret", "") +MAX_DOWNLOAD: int = Config.get("download_threads", 64) +PORT: int = Config.get("web_port", 8800) +PUBLICPORT: int = Config.get("web_publicport", 8800) +PUBLICHOST: int = Config.get("web_host", "") +BYOC: bool = Config.get("byoc", False) +TIMEOUT: int = Config.get("timeout", 30) MIN_RATE_TIMESTAMP = 1000 MIN_RATE = 500 REQUEST_BUFFER = 1024 * 8 diff --git a/container/web.py b/container/web.py index 55817d1..4b86270 100644 --- a/container/web.py +++ b/container/web.py @@ -543,7 +543,7 @@ async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): traceback.print_exc() async def main(): global cert, server - print(f"Loading...") + logger.info(f"Loading...") load_cert() import cluster await cluster.init() From 21c7682fb078d647176fcfbfa9e8430565ed92c0 Mon Sep 17 00:00:00 2001 From: SilianZ Date: Sun, 10 Mar 2024 02:52:22 +0800 Subject: [PATCH 5/5] =?UTF-8?q?:bug:=20=E4=BF=AE=E5=A4=8D=E6=BC=8F?= =?UTF-8?q?=E6=B4=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- container/config.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/container/config.py b/container/config.py index 4d91069..72993f5 100644 --- a/container/config.py +++ b/container/config.py @@ -1,5 +1,6 @@ from pathlib import Path import yaml +from typing import Union class CFG: def __init__(self, path: str) -> None: @@ -9,18 +10,18 @@ def __init__(self, path: str) -> None: self.load() def load(self): - with open(self.file, 'r', encoding="utf-8") as f: + with open(self.file, "r", encoding="utf-8") as f: self.cfg = yaml.load(f.read(), Loader=yaml.FullLoader) - def get(self, key, default): - value = self.cfg.get(key, None) + def get(self, key, default_): + value = self.cfg.get(key, default_) if value is None: - self.write(key, default) + self.write(key, default_) return value def write(self, key, value): self.cfg[key] = value - with open(self.file, 'w', encoding="utf-8") as f: + with open(self.file, "w", encoding="utf-8") as f: yaml.dump(data=self.cfg, stream=f, allow_unicode=True) Config: CFG = CFG("./config/config.yaml")