-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
122 lines (103 loc) · 3.64 KB
/
Copy pathmain.py
File metadata and controls
122 lines (103 loc) · 3.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
from fastapi import APIRouter, FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
import logging
import os
import traceback
from contextlib import asynccontextmanager
# Import services
from services.auth import init_sessions
from database.database_init import init_users_database
from services.directories import *
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan event handler"""
# Startup
logger.info("Starting Open312 application...")
# Create necessary directories
init_directories()
# Initialize database if needed
init_users_database()
# Initialize sessions from database
init_sessions()
# This will be implemented in database_init.py
logger.info("Application startup complete")
yield
# Shutdown
logger.info("Shutting down Open312 application...")
# Cleanup tasks here
logger.info("Application shutdown complete")
# Create FastAPI application
app = FastAPI(
title="Open312 新高考成绩管理系统",
description="A comprehensive exam score management system for new Gaokao",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan
)
# Configure CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure appropriately for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Import API routers
from static_router import router as static_router
from api.auth_api import auth_router
from api.admin_api import admin_router
from api.exams_api import router as exams_router
from api.cohorts_api import cohorts_router
# Include API routers
app.include_router(auth_router, prefix="/api")
app.include_router(admin_router, prefix="/api")
app.include_router(cohorts_router, prefix="/api")
app.include_router(exams_router, prefix="/api")
app.include_router(static_router)
app.mount("/static", StaticFiles(directory="static"), name="static")
# Configure templates
templates = Jinja2Templates(directory="templates")
# Exception handlers
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if "text/html" in request.headers.get("accept", ""):
return templates.TemplateResponse("error.html", {
"request": request,
"error_message": exc.detail
})
else:
print(traceback.format_exc())
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail, "status_code": exc.status_code}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
logger.error(f"Unexpected error: {exc}")
if "text/html" in request.headers.get("accept", ""):
return templates.TemplateResponse("error.html", {
"request": request,
"error_message": str(exc)
})
else:
print(traceback.format_exc())
return JSONResponse(
status_code=500,
content={"detail": "服务器内部错误,请尝试刷新", "status_code": 500}
)
# Health check endpoint
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {"status": "healthy", "message": "Open312 API is running"}
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=False)