server启动之后,填入callback

This commit is contained in:
liuwei
2025-04-23 11:42:58 +08:00
parent b476d30632
commit 1ab34cde0a
2 changed files with 25 additions and 21 deletions

View File

@@ -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("服务器启动失败")
print("服务器启动失败")