CaiYouHui后端fastapi实现

main.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # app/main.py - 简化版本
  2. from fastapi import FastAPI
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from app.logging_config import setup_logging_with_rotation
  5. import logging
  6. import os
  7. # 配置
  8. from .config import settings
  9. # 配置日志
  10. logging.basicConfig(
  11. level=logging.INFO,
  12. # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  13. # datefmt='%Y-%m-%d %H:%M:%S',
  14. # handlers=[
  15. # logging.StreamHandler(), # 控制台
  16. # logging.FileHandler('app/logs/app.log', encoding='utf-8') # 文件
  17. # ]
  18. )
  19. # 为特定模块设置更详细的日志
  20. logging.getLogger("app.api.v1").setLevel(logging.DEBUG)
  21. logging.getLogger("app.core.security").setLevel(logging.DEBUG)
  22. logger = logging.getLogger(__name__)
  23. logger.info("✅ 日志配置完成")
  24. # logger = setup_logging_with_rotation
  25. # 创建 FastAPI 应用
  26. app = FastAPI(
  27. title=settings.PROJECT_NAME,
  28. version=settings.VERSION,
  29. docs_url="/docs" if settings.DEBUG else None,
  30. redoc_url="/redoc" if settings.DEBUG else None
  31. )
  32. # 配置CORS
  33. if settings.BACKEND_CORS_ORIGINS:
  34. app.add_middleware(
  35. CORSMiddleware,
  36. allow_origins=settings.BACKEND_CORS_ORIGINS,
  37. allow_credentials=True,
  38. allow_methods=["*"],
  39. allow_headers=["*"],
  40. )
  41. # 导入并注册路由
  42. try:
  43. # 导入所有路由模块
  44. # from .api.v1.admin import router as admin_router
  45. from .api.v1.auth import router as auth_router
  46. from .api.v1.users import router as users_router
  47. # from .api.v1.verify import router as verify_router
  48. # 注册路由
  49. app.include_router(auth_router, prefix=settings.API_V1_PREFIX)
  50. app.include_router(users_router, prefix=settings.API_V1_PREFIX)
  51. # app.include_router(verify_router, prefix=settings.API_V1_PREFIX)
  52. logger.info("✅ API 路由注册成功")
  53. except ImportError as e:
  54. logger.warning(f"⚠️ 部分路由模块未找到: {e}")
  55. # 系统级路由
  56. @app.get("/health")
  57. async def health_check():
  58. return {"status": "healthy", "service": settings.PROJECT_NAME}
  59. @app.get("/")
  60. async def root():
  61. return {
  62. "message": f"Welcome to {settings.PROJECT_NAME} API",
  63. "version": settings.VERSION,
  64. "docs": "/docs"
  65. }
  66. if __name__ == "__main__":
  67. import uvicorn
  68. uvicorn.run(app, host="0.0.0.0", port=10003, reload=settings.DEBUG)