79 lines
2.1 KiB
Python
79 lines
2.1 KiB
Python
import os
|
||
import logging
|
||
|
||
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
|
||
from app.routes import auth_routes, wework_routes, glm_routes, message_routes
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||
datefmt="%Y-%m-%d %H:%M:%S",
|
||
)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
@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}")
|
||
|
||
yield # 应用在此处进入正常运行状态,接收请求
|
||
|
||
# 关闭数据库连接
|
||
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聊天服务",
|
||
}
|