| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- """
- FastAPI application entry point.
- Provides RESTful API for the annotation platform with JWT authentication.
- """
- from fastapi import FastAPI
- from fastapi.middleware.cors import CORSMiddleware
- from contextlib import asynccontextmanager
- from database import init_database
- from routers import project, task, annotation, auth, oauth, user, template, statistics, export, external
- from middleware.auth_middleware import AuthMiddleware
- @asynccontextmanager
- async def lifespan(app: FastAPI):
- """
- Application lifespan manager.
- Initializes database on startup.
- """
- # Startup: Initialize database
- init_database()
- yield
- # Shutdown: cleanup if needed
- # Create FastAPI application instance
- app = FastAPI(
- title="Annotation Platform API",
- description="RESTful API for data annotation management with JWT authentication",
- version="1.0.0",
- lifespan=lifespan
- )
- # Configure CORS middleware (must be added first)
- app.add_middleware(
- CORSMiddleware,
- allow_origins=[
- "http://localhost:4200", # Frontend dev server
- "http://localhost:3000", # Alternative frontend port
- ],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- # Add authentication middleware (after CORS)
- app.add_middleware(AuthMiddleware)
- # Include routers
- app.include_router(auth.router)
- app.include_router(oauth.router)
- app.include_router(project.router)
- app.include_router(task.router)
- app.include_router(annotation.router)
- app.include_router(user.router)
- app.include_router(template.router)
- app.include_router(statistics.router)
- app.include_router(export.router)
- app.include_router(external.router)
- @app.get("/")
- async def root():
- """Root endpoint - health check"""
- return {
- "message": "Annotation Platform API",
- "status": "running",
- "version": "1.0.0"
- }
- @app.get("/health")
- async def health_check():
- """
- 健康检查接口
- 检查服务状态和数据库连接
- """
- import time
- from database import get_db_connection, db_config
-
- start_time = time.time()
- health_status = {
- "status": "healthy",
- "version": "1.0.0",
- "checks": {}
- }
-
- # 检查数据库连接
- try:
- with get_db_connection() as conn:
- cursor = conn.cursor()
- cursor.execute("SELECT 1")
- cursor.fetchone()
- health_status["checks"]["database"] = {
- "status": "healthy",
- "type": db_config.db_type
- }
- except Exception as e:
- health_status["status"] = "unhealthy"
- health_status["checks"]["database"] = {
- "status": "unhealthy",
- "error": str(e)
- }
-
- # 响应时间
- health_status["response_time_ms"] = round((time.time() - start_time) * 1000, 2)
-
- return health_status
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app, host="0.0.0.0", port=8003)
|