Files
chat_app/backend/app/main.py
2025-12-12 03:29:09 +08:00

135 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from contextlib import asynccontextmanager
from pymongo import AsyncMongoClient
from beanie import init_beanie, PydanticObjectId
from app.models import models
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os
from app.routes import auth_routes, wework_routes, glm_routes, message_routes
@asynccontextmanager
async def lifespan(app: FastAPI):
# 从环境变量获取数据库配置
mongodb_url = os.getenv("MONGODB_URL", "mongodb://localhost:27017")
database_name = os.getenv("DATABASE_NAME", "douba_chat_dev")
# 初始化数据库连接
client = AsyncMongoClient(mongodb_url)
await init_beanie(
database=client[database_name], document_models=models
) # 批量注册模型
print(f"🗄️ 数据库连接成功: {database_name}")
# 初始化GLM服务,确保默认角色存在
try:
from app.services.glm_service import get_glm_service
glm_service = get_glm_service()
await glm_service.ensure_default_role()
print(f"✅ GLM角色配置初始化完成")
except Exception as e:
print(f"⚠️ GLM角色配置初始化失败: {e}")
yield # 应用在此处进入正常运行状态,接收请求
# 关闭GLM服务
try:
from app.services.glm_service import close_glm_service
close_glm_service()
print(f"GLM服务已关闭")
except Exception as e:
print(f"关闭GLM服务时出错: {e}")
# 关闭数据库连接
await client.close()
print(f"数据库连接关闭")
# 创建FastAPI应用
app = FastAPI(
title="企业微信认证服务",
description="获取和管理企业微信access_token的API服务",
version="1.0.0",
docs_url="/api/docs",
redoc_url="/api/redoc",
lifespan=lifespan,
)
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注册路由
app.include_router(auth_routes.router, prefix="/api")
app.include_router(wework_routes.router, prefix="/api")
app.include_router(glm_routes.router, prefix="/api")
app.include_router(message_routes.router, prefix="/api")
@app.get("/api/")
async def root():
"""
根端点,提供API基本信息
"""
return {
"service": "企业微信认证与会话存档服务",
"version": "1.0.0",
"description": "获取和管理企业微信access_token,会话存档功能,以及DeepSeek AI聊天服务",
"endpoints": {
"docs": "/api/docs",
"redoc": "/api/redoc",
"auth": {"token": "/api/auth/token", "token_info": "/api/auth/token/info"},
"wework": {
"health": "/api/wework/health",
"chat": "/api/wework/chat",
"media": "/api/wework/media",
"decrypt": "/api/wework/decrypt",
"config": "/api/wework/config",
},
"glm": {
"root": "/api/glm/",
"role": "/api/glm/role",
"chat": "/api/glm/chat",
"conversations": "/api/glm/conversations/{conversation_id}",
},
"messages": {
"load": "/api/messages/load",
"list": "/api/messages/",
"stats": "/api/messages/stats",
"detail": "/api/messages/{msgid}",
},
},
}
def main():
"""
主函数,启动FastAPI服务器
"""
# 从环境变量获取主机和端口,使用默认值
host = os.getenv("APP_HOST", "0.0.0.0")
port = int(os.getenv("APP_PORT", "8000"))
print("启动企业微信认证与会话存档服务...")
print(f"API文档地址: http://{host}:{port}/docs")
print(f"API根地址: http://{host}:{port}")
print("企业微信会话存档API: /api/wework/*")
print("DeepSeek AI聊天API: /api/glm/*")
print("消息管理API: /api/messages/*")
uvicorn.run("app.main:app", host=host, port=port, reload=True, log_level="info")
if __name__ == "__main__":
main()