ai_project_v1/b3dm/b3dm_api.py
2026-01-14 11:37:35 +08:00

60 lines
1.6 KiB
Python

from sanic import Sanic, Request, json
from sanic_cors import CORS
import logging
import time
from earthwork_api import earthwork_bp
from terrain_api import terrain_bp
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 创建Sanic应用
app = Sanic("TerrainAnalysisAPI")
# 显式注册蓝图
app.blueprint(earthwork_bp)
app.blueprint(terrain_bp)
CORS(app, automatic_options=True)
# 中间件:请求计时
@app.middleware("request")
async def add_start_time(request: Request):
request.ctx.start_time = time.time()
@app.middleware("response")
async def add_response_time(request: Request, response):
if hasattr(request.ctx, "start_time"):
process_time = (time.time() - request.ctx.start_time) * 1000
response.headers["X-Process-Time"] = f"{process_time:.2f}ms"
@app.get("/api/v1/health")
async def health_check(request: Request):
"""健康检查"""
return json({
"status": "healthy",
"timestamp": time.time(),
"service": "terrain-analysis-api",
"version": "1.0.0"
})
# 错误处理
@app.exception(Exception)
async def handle_exception(request: Request, exception):
"""全局异常处理"""
logger.error(f"未处理的异常: {exception}")
return json({
"error": "服务器内部错误",
"message": str(exception) if app.debug else "请稍后重试",
"success": False
}, status=500)
if __name__ == "__main__":
# 启动服务器
app.run(
host="0.0.0.0",
port=8000,
debug=True, # 生产环境设为False
access_log=True,
auto_reload=True
)