vector.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # 矢量数据API
  2. from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, BackgroundTasks, Query
  3. from fastapi.responses import FileResponse
  4. from sqlalchemy.orm import Session
  5. from ..database import get_db
  6. from ..services import vector_service
  7. from ..services.admin_boundary_service import get_boundary_geojson_by_name
  8. import os
  9. import shutil
  10. from typing import List
  11. router = APIRouter()
  12. @router.post("/import", summary="导入GeoJSON文件", description="将GeoJSON文件导入到数据库中")
  13. async def import_vector_data(file: UploadFile = File(...), db: Session = Depends(get_db)):
  14. """导入GeoJSON文件到数据库"""
  15. # 检查文件类型
  16. if not file.filename.endswith('.geojson'):
  17. raise HTTPException(status_code=400, detail="只支持GeoJSON文件")
  18. return await vector_service.import_vector_data(file, db)
  19. @router.get("/boundary", summary="按名称获取边界", description="按县/市/省名称获取边界GeoJSON")
  20. def get_boundary(name: str = Query(...), level: str = Query("auto"), db: Session = Depends(get_db)):
  21. """按名称和层级获取边界。level: county/city/province/auto"""
  22. try:
  23. return get_boundary_geojson_by_name(db, name, level)
  24. except Exception as e:
  25. raise HTTPException(status_code=404, detail=str(e))
  26. @router.get("/{vector_id}", summary="获取矢量数据", description="根据ID获取一条矢量数据记录")
  27. def get_vector_data(vector_id: int, db: Session = Depends(get_db)):
  28. """获取指定ID的矢量数据"""
  29. return vector_service.get_vector_data(db, vector_id)
  30. @router.get("/{vector_id}/export", summary="导出矢量数据", description="将指定ID的矢量数据导出为GeoJSON文件")
  31. async def export_vector_data(vector_id: int, db: Session = Depends(get_db)):
  32. """导出指定ID的矢量数据为GeoJSON文件"""
  33. result = vector_service.export_vector_data(db, vector_id)
  34. # 检查文件是否存在
  35. if not os.path.exists(result["file_path"]):
  36. if "temp_dir" in result and os.path.exists(result["temp_dir"]):
  37. shutil.rmtree(result["temp_dir"])
  38. raise HTTPException(status_code=404, detail="导出文件不存在")
  39. # 返回文件下载
  40. return FileResponse(
  41. path=result["file_path"],
  42. filename=os.path.basename(result["file_path"]),
  43. media_type="application/json",
  44. background=BackgroundTasks().add_task(shutil.rmtree, result["temp_dir"]) if "temp_dir" in result else None
  45. )
  46. @router.get("/export/all", summary="导出矢量数据", description="将指定的矢量数据表导出为GeoJSON文件")
  47. async def export_all_vector_data_api(table_name: str = "vector_data", db: Session = Depends(get_db)):
  48. """导出指定矢量数据表为GeoJSON文件
  49. Args:
  50. table_name (str): 要导出的矢量数据表名,默认为'vector_data'
  51. db (Session): 数据库会话
  52. Returns:
  53. FileResponse: GeoJSON文件下载响应
  54. """
  55. result = vector_service.export_all_vector_data(db, table_name)
  56. # 检查文件是否存在
  57. if not os.path.exists(result["file_path"]):
  58. if "temp_dir" in result and os.path.exists(result["temp_dir"]):
  59. shutil.rmtree(result["temp_dir"])
  60. raise HTTPException(status_code=404, detail="导出文件不存在")
  61. # 返回文件下载
  62. return FileResponse(
  63. path=result["file_path"],
  64. filename=os.path.basename(result["file_path"]),
  65. media_type="application/json",
  66. background=BackgroundTasks().add_task(shutil.rmtree, result["temp_dir"]) if "temp_dir" in result else None
  67. )
  68. @router.post("/export/batch", summary="批量导出矢量数据", description="将多个ID的矢量数据批量导出为GeoJSON文件")
  69. async def export_vector_data_batch(vector_ids: List[int], db: Session = Depends(get_db)):
  70. """批量导出矢量数据为GeoJSON文件"""
  71. result = vector_service.export_vector_data_batch(db, vector_ids)
  72. # 检查文件是否存在
  73. if not os.path.exists(result["file_path"]):
  74. if "temp_dir" in result and os.path.exists(result["temp_dir"]):
  75. shutil.rmtree(result["temp_dir"])
  76. raise HTTPException(status_code=404, detail="导出文件不存在")
  77. # 返回文件下载
  78. return FileResponse(
  79. path=result["file_path"],
  80. filename=os.path.basename(result["file_path"]),
  81. media_type="application/json",
  82. background=BackgroundTasks().add_task(shutil.rmtree, result["temp_dir"]) if "temp_dir" in result else None
  83. )