From 1ab34cde0ad89be159ebafc0b2e5532e82908bd7 Mon Sep 17 00:00:00 2001 From: liuwei Date: Wed, 23 Apr 2025 11:42:58 +0800 Subject: [PATCH] =?UTF-8?q?server=E5=90=AF=E5=8A=A8=E4=B9=8B=E5=90=8E?= =?UTF-8?q?=EF=BC=8C=E5=A1=AB=E5=85=A5callback?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gewechat/api/start_server.py | 22 ++++++++++++++-------- gewechat/client.py | 24 +++++++++++------------- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/gewechat/api/start_server.py b/gewechat/api/start_server.py index 8f0daaa..4f12edc 100644 --- a/gewechat/api/start_server.py +++ b/gewechat/api/start_server.py @@ -5,10 +5,12 @@ import uvicorn from fastapi import FastAPI from gewechat.api.callback import router as callback_router +from gewechat.client import gewe_client # 配置日志 logger = logging.getLogger(__name__) + def is_port_in_use(port, host='0.0.0.0'): """检查端口是否被占用""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: @@ -18,6 +20,7 @@ def is_port_in_use(port, host='0.0.0.0'): except socket.error: return True + def start_fastapi_server(host="0.0.0.0", port=8999): """启动FastAPI服务器""" # 检查端口是否被占用 @@ -31,18 +34,18 @@ def start_fastapi_server(host="0.0.0.0", port=8999): else: logger.error("无法找到可用端口,服务器启动失败") return False - + try: app = FastAPI() app.include_router(callback_router) - + # 添加健康检查路由 @app.get("/health") async def health_check(): return {"status": "ok"} - + logger.info(f"正在启动FastAPI服务器,地址: http://{host}:{port}") - + # 使用线程启动uvicorn服务器 server_thread = threading.Thread( target=uvicorn.run, @@ -53,33 +56,36 @@ def start_fastapi_server(host="0.0.0.0", port=8999): server_thread.start() logger.info(f"FastAPI 服务已在 http://{host}:{port} 启动") logger.info(f"回调URL: http://{host}:{port}/gewechat/callback") - + # 启动之后,填入callback + gewe_client.client_set_callback() # 返回启动的端口,以便调用者知道实际使用的端口 return port except Exception as e: logger.error(f"启动FastAPI服务器失败: {e}", exc_info=True) return False + if __name__ == '__main__': # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) - + # 启动服务器 port = start_fastapi_server() if port: print(f"服务器启动成功,端口: {port}") print(f"回调URL: http://localhost:{port}/gewechat/callback") print(f"健康检查URL: http://localhost:{port}/health") - + # 保持主线程运行 try: import time + while True: time.sleep(1) except KeyboardInterrupt: print("服务器已停止") else: - print("服务器启动失败") \ No newline at end of file + print("服务器启动失败") diff --git a/gewechat/client.py b/gewechat/client.py index c274c69..19f175b 100644 --- a/gewechat/client.py +++ b/gewechat/client.py @@ -25,13 +25,21 @@ class Client: base_url=self.base_url, token=self.gewechat_token ) - # 登录, 自动创建二维码,扫码后自动登录 app_id, error_msg = self.client.login(app_id=self.app_id) - if error_msg: logger.error("登录失败") return - # 休眠等待server启动,防止回调设置失败 + + # 如果启动时,配置文件中的app_id为空,那么将app_id写入配置文件 + if not self.app_id and app_id: + config["Gewechat"]["app_id"] = app_id + with open(self.config_path, "w", encoding="utf-8") as f: + toml.dump(config, f) + logger.info(f"已将新的APP_ID: {app_id} 写入配置文件") + self.app_id = app_id + + def client_set_callback(self): + """在server启动后调用此方法设置回调""" max_retries = 5 retry_interval = 5 # 秒 for attempt in range(1, max_retries + 1): @@ -45,15 +53,5 @@ class Client: else: logger.error("set_callback 多次重试后仍失败,请检查server状态。") - # 如果启动时,配置文件中的app_id为空,那么将app_id写入配置文件 - if not self.app_id and app_id: - # 更新 config.toml 文件中的 app_id - config["Gewechat"]["app_id"] = app_id - with open(self.config_path, "w", encoding="utf-8") as f: - toml.dump(config, f) - logger.info(f"已将新的APP_ID: {app_id} 写入配置文件") - # 同时更新当前实例的 app_id - self.app_id = app_id - # 项目全局唯一 client 实例 gewe_client = Client().client \ No newline at end of file