city.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. from sqlalchemy import Column, Integer, String, Text, Index, JSON
  2. from sqlalchemy.dialects.postgresql import JSONB
  3. from geoalchemy2 import Geometry
  4. from app.database import Base
  5. from shapely.geometry import shape, MultiPolygon, Polygon
  6. import json
  7. class City(Base):
  8. """市级行政区划地理数据表"""
  9. __tablename__ = "cities"
  10. # 字段映射字典
  11. FIELD_MAPPING = {
  12. '市名': 'name',
  13. '市代码': 'code',
  14. '省名': 'province_name',
  15. '省代码': 'province_code'
  16. }
  17. # 反向映射字典
  18. REVERSE_FIELD_MAPPING = {v: k for k, v in FIELD_MAPPING.items()}
  19. id = Column(Integer, primary_key=True, index=True)
  20. name = Column(String(100), nullable=False, comment="市名")
  21. code = Column(Integer, nullable=False, unique=True, comment="市代码")
  22. province_name = Column(String(100), nullable=False, comment="省名")
  23. province_code = Column(Integer, nullable=False, comment="省代码")
  24. # 使用PostGIS的几何类型来存储多边形数据
  25. geometry = Column(Geometry('MULTIPOLYGON', srid=4326), nullable=False, comment="市级行政区划的几何数据")
  26. # 存储完整的GeoJSON数据
  27. geojson = Column(JSON, nullable=False, comment="完整的GeoJSON数据")
  28. # 显式定义索引
  29. __table_args__ = (
  30. Index('idx_cities_name', 'name'),
  31. Index('idx_cities_code', 'code'),
  32. Index('idx_cities_province_code', 'province_code'),
  33. #Index('idx_cities_geometry', 'geometry', postgresql_using='gist'),
  34. )
  35. @classmethod
  36. def from_geojson_feature(cls, feature):
  37. """从GeoJSON Feature创建City实例
  38. Args:
  39. feature: GeoJSON Feature对象
  40. Returns:
  41. City: 新创建的City实例
  42. """
  43. properties = feature['properties']
  44. # 转换中文字段名为英文
  45. mapped_properties = {
  46. cls.FIELD_MAPPING.get(k, k): v
  47. for k, v in properties.items()
  48. }
  49. # 将GeoJSON geometry转换为EWKT格式(SRID=4326)
  50. geometry = feature['geometry']
  51. geom = shape(geometry)
  52. # 统一为 MultiPolygon 以匹配列类型
  53. if isinstance(geom, Polygon):
  54. geom = MultiPolygon([geom])
  55. wkt = f"SRID=4326;{geom.wkt}"
  56. # 创建实例
  57. city = cls(
  58. **mapped_properties,
  59. geometry=wkt,
  60. geojson=feature
  61. )
  62. return city
  63. def to_geojson_feature(self):
  64. """将City实例转换为GeoJSON Feature
  65. Returns:
  66. dict: GeoJSON Feature对象
  67. """
  68. properties = {}
  69. # 转换英文字段名为中文
  70. for eng_field, cn_field in self.REVERSE_FIELD_MAPPING.items():
  71. if hasattr(self, eng_field):
  72. properties[cn_field] = getattr(self, eng_field)
  73. return {
  74. 'type': 'Feature',
  75. 'properties': properties,
  76. 'geometry': self.geometry
  77. }