123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- import time
- import traceback
- from fastapi import FastAPI
- from .api import vector, raster, cd_prediction, unit_grouping, water, agricultural_input, cd_flux_removal, cd_flux
- from .database import engine, Base
- from fastapi.middleware.cors import CORSMiddleware
- import logging
- import sys
- import os
- from fastapi import FastAPI, HTTPException, Request, status
- from fastapi.responses import JSONResponse
- from app.log.logger import get_logger, ExceptionLogger, setup_logging # 导入日志模块
- from app.log import error
- # 配置日志
- from app.log.logger import get_logger
- logger = get_logger(__name__)
- def safe_create_tables():
- """
- 安全地创建数据库表
-
- @description: 直接创建表结构,跳过迁移检查
- """
- try:
- # 直接创建数据库表
- Base.metadata.create_all(bind=engine)
- logger.info("数据库表结构创建完成")
-
- except Exception as e:
- logger.error(f"数据库表创建失败: {str(e)}")
- logger.error("请检查数据库连接和表结构定义")
- # 不要退出,继续运行应用
- # sys.exit(1) # 注释掉这行,避免应用退出
- # 执行数据库初始化
- safe_create_tables()
- app = FastAPI(
- title="地图数据处理系统",
- description="一个用于处理地图数据的API系统",
- version="1.0.0",
- openapi_tags=[
- # ...(保持原有标签定义不变)
- ]
- )
- # ---------------------------
- # 添加 CORS 配置(关键修改)
- # ---------------------------
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["https://soilgd.com", "http://localhost:5173", "https://www.soilgd.com"],
- allow_methods=["*"],
- allow_headers=["*"],
- allow_credentials=True,
- )
- # 注册路由(保持原有路由注册不变)
- app.include_router(vector.router, prefix="/api/vector", tags=["vector"])
- app.include_router(raster.router, prefix="/api/raster", tags=["raster"])
- app.include_router(cd_prediction.router, prefix="/api/cd-prediction", tags=["cd-prediction"])
- app.include_router(unit_grouping.router, prefix="/api/unit-grouping", tags=["unit-grouping"])
- app.include_router(water.router, prefix="/api/water", tags=["water"])
- app.include_router(agricultural_input.router, prefix="/api/agricultural-input", tags=["agricultural-input"])
- app.include_router(cd_flux_removal.router, prefix="/api/cd-flux-removal", tags=["cd-flux-removal"])
- app.include_router(cd_flux.router, prefix="/api/cd-flux", tags=["cd-flux"])
- app.include_router(error.router, prefix="/api/errors", tags=["errors"])
- @app.get("/")
- async def root():
- return {"message": "Welcome to the GIS Data Management API"}
- # 可选:添加健康检查端点
- @app.get("/health")
- async def health_check():
- return {"status": "healthy", "database": "connected"}
- # 全局异常处理器
- @app.exception_handler(Exception)
- async def global_exception_handler(request: Request, exc: Exception):
- """全局异常处理器"""
- # 生成唯一错误ID
- error_id = f"ERR-{int(time.time() * 1000)}"
- # 获取完整的堆栈跟踪
- tb_str = traceback.format_exc()
- # 记录完整错误信息(包含堆栈跟踪)
- logger.error(f"ErrorID: {error_id} - {str(exc)}\n{tb_str}")
- return JSONResponse(
- status_code=500,
- content={
- "code": error_id,
- "message": "Internal server error",
- "documentation": f"/api/errors/{error_id}"
- }
- )
- # 自定义HTTP异常处理
- @app.exception_handler(HTTPException)
- async def http_exception_handler(request: Request, exc: HTTPException):
- """HTTP异常处理器"""
- # 生成错误ID
- error_id = f"HTTP-{exc.status_code}-{int(time.time() * 1000)}"
- # 记录到错误日志
- logger.error(f"ErrorID: {error_id} - HTTP {exc.status_code}: {exc.detail}")
- return JSONResponse(
- status_code=exc.status_code,
- content={
- "code": error_id,
- "message": exc.detail,
- "documentation": f"/api/errors/{error_id}"
- }
- )
|