server启动之后,填入callback
This commit is contained in:
@@ -5,10 +5,12 @@ import uvicorn
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from gewechat.api.callback import router as callback_router
|
from gewechat.api.callback import router as callback_router
|
||||||
|
from gewechat.client import gewe_client
|
||||||
|
|
||||||
# 配置日志
|
# 配置日志
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def is_port_in_use(port, host='0.0.0.0'):
|
def is_port_in_use(port, host='0.0.0.0'):
|
||||||
"""检查端口是否被占用"""
|
"""检查端口是否被占用"""
|
||||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
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:
|
except socket.error:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def start_fastapi_server(host="0.0.0.0", port=8999):
|
def start_fastapi_server(host="0.0.0.0", port=8999):
|
||||||
"""启动FastAPI服务器"""
|
"""启动FastAPI服务器"""
|
||||||
# 检查端口是否被占用
|
# 检查端口是否被占用
|
||||||
@@ -31,18 +34,18 @@ def start_fastapi_server(host="0.0.0.0", port=8999):
|
|||||||
else:
|
else:
|
||||||
logger.error("无法找到可用端口,服务器启动失败")
|
logger.error("无法找到可用端口,服务器启动失败")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
app.include_router(callback_router)
|
app.include_router(callback_router)
|
||||||
|
|
||||||
# 添加健康检查路由
|
# 添加健康检查路由
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
async def health_check():
|
async def health_check():
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
logger.info(f"正在启动FastAPI服务器,地址: http://{host}:{port}")
|
logger.info(f"正在启动FastAPI服务器,地址: http://{host}:{port}")
|
||||||
|
|
||||||
# 使用线程启动uvicorn服务器
|
# 使用线程启动uvicorn服务器
|
||||||
server_thread = threading.Thread(
|
server_thread = threading.Thread(
|
||||||
target=uvicorn.run,
|
target=uvicorn.run,
|
||||||
@@ -53,33 +56,36 @@ def start_fastapi_server(host="0.0.0.0", port=8999):
|
|||||||
server_thread.start()
|
server_thread.start()
|
||||||
logger.info(f"FastAPI 服务已在 http://{host}:{port} 启动")
|
logger.info(f"FastAPI 服务已在 http://{host}:{port} 启动")
|
||||||
logger.info(f"回调URL: http://{host}:{port}/gewechat/callback")
|
logger.info(f"回调URL: http://{host}:{port}/gewechat/callback")
|
||||||
|
# 启动之后,填入callback
|
||||||
|
gewe_client.client_set_callback()
|
||||||
# 返回启动的端口,以便调用者知道实际使用的端口
|
# 返回启动的端口,以便调用者知道实际使用的端口
|
||||||
return port
|
return port
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"启动FastAPI服务器失败: {e}", exc_info=True)
|
logger.error(f"启动FastAPI服务器失败: {e}", exc_info=True)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# 配置日志
|
# 配置日志
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||||
)
|
)
|
||||||
|
|
||||||
# 启动服务器
|
# 启动服务器
|
||||||
port = start_fastapi_server()
|
port = start_fastapi_server()
|
||||||
if port:
|
if port:
|
||||||
print(f"服务器启动成功,端口: {port}")
|
print(f"服务器启动成功,端口: {port}")
|
||||||
print(f"回调URL: http://localhost:{port}/gewechat/callback")
|
print(f"回调URL: http://localhost:{port}/gewechat/callback")
|
||||||
print(f"健康检查URL: http://localhost:{port}/health")
|
print(f"健康检查URL: http://localhost:{port}/health")
|
||||||
|
|
||||||
# 保持主线程运行
|
# 保持主线程运行
|
||||||
try:
|
try:
|
||||||
import time
|
import time
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("服务器已停止")
|
print("服务器已停止")
|
||||||
else:
|
else:
|
||||||
print("服务器启动失败")
|
print("服务器启动失败")
|
||||||
|
|||||||
@@ -25,13 +25,21 @@ class Client:
|
|||||||
base_url=self.base_url,
|
base_url=self.base_url,
|
||||||
token=self.gewechat_token
|
token=self.gewechat_token
|
||||||
)
|
)
|
||||||
# 登录, 自动创建二维码,扫码后自动登录
|
|
||||||
app_id, error_msg = self.client.login(app_id=self.app_id)
|
app_id, error_msg = self.client.login(app_id=self.app_id)
|
||||||
|
|
||||||
if error_msg:
|
if error_msg:
|
||||||
logger.error("登录失败")
|
logger.error("登录失败")
|
||||||
return
|
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
|
max_retries = 5
|
||||||
retry_interval = 5 # 秒
|
retry_interval = 5 # 秒
|
||||||
for attempt in range(1, max_retries + 1):
|
for attempt in range(1, max_retries + 1):
|
||||||
@@ -45,15 +53,5 @@ class Client:
|
|||||||
else:
|
else:
|
||||||
logger.error("set_callback 多次重试后仍失败,请检查server状态。")
|
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 实例
|
# 项目全局唯一 client 实例
|
||||||
gewe_client = Client().client
|
gewe_client = Client().client
|
||||||
Reference in New Issue
Block a user