main.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """
  2. FastAPI application entry point.
  3. Provides RESTful API for the annotation platform with SSO authentication.
  4. """
  5. import logging
  6. from fastapi import FastAPI
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from contextlib import asynccontextmanager
  9. from database import init_database
  10. from routers import project, task, annotation, oauth, user, template, statistics, export, external
  11. from middleware.auth_middleware import AuthMiddleware
  12. # 配置日志
  13. logging.basicConfig(
  14. level=logging.DEBUG,
  15. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  16. datefmt='%Y-%m-%d %H:%M:%S'
  17. )
  18. @asynccontextmanager
  19. async def lifespan(app: FastAPI):
  20. """
  21. Application lifespan manager.
  22. Initializes database on startup.
  23. """
  24. # Startup: Initialize database
  25. init_database()
  26. yield
  27. # Shutdown: cleanup if needed
  28. # Create FastAPI application instance
  29. app = FastAPI(
  30. title="Annotation Platform API",
  31. description="RESTful API for data annotation management with SSO authentication",
  32. version="1.0.0",
  33. lifespan=lifespan
  34. )
  35. # Configure CORS middleware (must be added first)
  36. app.add_middleware(
  37. CORSMiddleware,
  38. allow_origins=[
  39. "http://localhost:4200", # Frontend dev server
  40. "http://localhost:3000", # Alternative frontend port
  41. ],
  42. allow_credentials=True,
  43. allow_methods=["*"],
  44. allow_headers=["*"],
  45. )
  46. # Add authentication middleware (after CORS)
  47. app.add_middleware(AuthMiddleware)
  48. # Include routers
  49. app.include_router(oauth.router)
  50. app.include_router(project.router)
  51. app.include_router(task.router)
  52. app.include_router(annotation.router)
  53. app.include_router(user.router)
  54. app.include_router(template.router)
  55. app.include_router(statistics.router)
  56. app.include_router(export.router)
  57. app.include_router(external.router)
  58. @app.get("/")
  59. async def root():
  60. """Root endpoint - health check"""
  61. return {
  62. "message": "Annotation Platform API",
  63. "status": "running",
  64. "version": "1.0.0"
  65. }
  66. @app.get("/health")
  67. async def health_check():
  68. """
  69. 健康检查接口
  70. 检查服务状态和数据库连接
  71. """
  72. import time
  73. from database import get_db_connection, db_config
  74. start_time = time.time()
  75. health_status = {
  76. "status": "healthy",
  77. "version": "1.0.0",
  78. "checks": {}
  79. }
  80. # 检查数据库连接
  81. try:
  82. with get_db_connection() as conn:
  83. cursor = conn.cursor()
  84. cursor.execute("SELECT 1")
  85. cursor.fetchone()
  86. health_status["checks"]["database"] = {
  87. "status": "healthy",
  88. "type": db_config.db_type
  89. }
  90. except Exception as e:
  91. health_status["status"] = "unhealthy"
  92. health_status["checks"]["database"] = {
  93. "status": "unhealthy",
  94. "error": str(e)
  95. }
  96. # 响应时间
  97. health_status["response_time_ms"] = round((time.time() - start_time) * 1000, 2)
  98. return health_status
  99. if __name__ == "__main__":
  100. import uvicorn
  101. uvicorn.run(app, host="0.0.0.0", port=8003)