main.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from fastapi import FastAPI
  2. from .api import vector, raster, cd_prediction, unit_grouping, water, agricultural_input, cd_flux_removal, cd_flux
  3. from .database import engine, Base
  4. from fastapi.middleware.cors import CORSMiddleware
  5. import logging
  6. import sys
  7. import os
  8. # 设置日志 - 检查是否已经配置过,避免重复配置
  9. if not logging.getLogger().handlers:
  10. logging.basicConfig(level=logging.INFO)
  11. logger = logging.getLogger(__name__)
  12. def safe_create_tables():
  13. """
  14. 安全地创建数据库表
  15. @description: 直接创建表结构,跳过迁移检查
  16. """
  17. try:
  18. # 直接创建数据库表
  19. Base.metadata.create_all(bind=engine)
  20. logger.info("数据库表结构创建完成")
  21. except Exception as e:
  22. logger.error(f"数据库表创建失败: {str(e)}")
  23. logger.error("请检查数据库连接和表结构定义")
  24. # 不要退出,继续运行应用
  25. # sys.exit(1) # 注释掉这行,避免应用退出
  26. # 执行数据库初始化
  27. safe_create_tables()
  28. app = FastAPI(
  29. title="地图数据处理系统",
  30. description="一个用于处理地图数据的API系统",
  31. version="1.0.0",
  32. openapi_tags=[
  33. # ...(保持原有标签定义不变)
  34. ]
  35. )
  36. # ---------------------------
  37. # 添加 CORS 配置(关键修改)
  38. # ---------------------------
  39. app.add_middleware(
  40. CORSMiddleware,
  41. allow_origins=["https://soilgd.com", "http://localhost:5173", "https://www.soilgd.com"],
  42. allow_methods=["*"],
  43. allow_headers=["*"],
  44. allow_credentials=True,
  45. )
  46. # 注册路由(保持原有路由注册不变)
  47. app.include_router(vector.router, prefix="/api/vector", tags=["vector"])
  48. app.include_router(raster.router, prefix="/api/raster", tags=["raster"])
  49. app.include_router(cd_prediction.router, prefix="/api/cd-prediction", tags=["cd-prediction"])
  50. app.include_router(unit_grouping.router, prefix="/api/unit-grouping", tags=["unit-grouping"])
  51. app.include_router(water.router, prefix="/api/water", tags=["water"])
  52. app.include_router(agricultural_input.router, prefix="/api/agricultural-input", tags=["agricultural-input"])
  53. app.include_router(cd_flux_removal.router, prefix="/api/cd-flux-removal", tags=["cd-flux-removal"])
  54. app.include_router(cd_flux.router, prefix="/api/cd-flux", tags=["cd-flux"])
  55. @app.get("/")
  56. async def root():
  57. return {"message": "Welcome to the GIS Data Management API"}
  58. # 可选:添加健康检查端点
  59. @app.get("/health")
  60. async def health_check():
  61. return {"status": "healthy", "database": "connected"}