1
0

main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """FastAPI主应用"""
  2. from fastapi import FastAPI
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from ..config import get_settings, validate_config, print_config
  5. from .routes import trip, poi, map as map_routes
  6. # 获取配置
  7. settings = get_settings()
  8. # 创建FastAPI应用
  9. app = FastAPI(
  10. title=settings.app_name,
  11. version=settings.app_version,
  12. description="基于HelloAgents框架的智能旅行规划助手API",
  13. docs_url="/docs",
  14. redoc_url="/redoc"
  15. )
  16. # 配置CORS
  17. app.add_middleware(
  18. CORSMiddleware,
  19. allow_origins=settings.get_cors_origins_list(),
  20. allow_credentials=True,
  21. allow_methods=["*"],
  22. allow_headers=["*"],
  23. )
  24. # 注册路由
  25. app.include_router(trip.router, prefix="/api")
  26. app.include_router(poi.router, prefix="/api")
  27. app.include_router(map_routes.router, prefix="/api")
  28. @app.on_event("startup")
  29. async def startup_event():
  30. """应用启动事件"""
  31. print("\n" + "="*60)
  32. print(f"🚀 {settings.app_name} v{settings.app_version}")
  33. print("="*60)
  34. # 打印配置信息
  35. print_config()
  36. # 验证配置
  37. try:
  38. validate_config()
  39. print("\n✅ 配置验证通过")
  40. except ValueError as e:
  41. print(f"\n❌ 配置验证失败:\n{e}")
  42. print("\n请检查.env文件并确保所有必要的配置项都已设置")
  43. raise
  44. print("\n" + "="*60)
  45. print("📚 API文档: http://localhost:8000/docs")
  46. print("📖 ReDoc文档: http://localhost:8000/redoc")
  47. print("="*60 + "\n")
  48. @app.on_event("shutdown")
  49. async def shutdown_event():
  50. """应用关闭事件"""
  51. print("\n" + "="*60)
  52. print("👋 应用正在关闭...")
  53. print("="*60 + "\n")
  54. @app.get("/")
  55. async def root():
  56. """根路径"""
  57. return {
  58. "name": settings.app_name,
  59. "version": settings.app_version,
  60. "status": "running",
  61. "docs": "/docs",
  62. "redoc": "/redoc"
  63. }
  64. @app.get("/health")
  65. async def health():
  66. """健康检查"""
  67. return {
  68. "status": "healthy",
  69. "service": settings.app_name,
  70. "version": settings.app_version
  71. }
  72. if __name__ == "__main__":
  73. import uvicorn
  74. uvicorn.run(
  75. "app.api.main:app",
  76. host=settings.host,
  77. port=settings.port,
  78. reload=True
  79. )