【问题标题】:How to create a Marshmallow SQL schema for GeoJson如何为 GeoJson 创建 Marshmallow SQL 模式
【发布时间】:2020-10-31 13:15:25
【问题描述】:

我正在尝试使用烧瓶创建APISQLAlchemyMarshmallowPostGIS,返回 GeoJsonFeatureCollection。我希望能够使用任何地理对象(PointPolygone、...)。

我尝试了很多方法,但从未成功重新创建 GeoJson FeatureCollection 格式。可以将形状强制为棉花糖模式吗?

这是 SQLAlchemy 模型:

class Locations(db.Model):
    __tablename__ = 'locations'
    id: int = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name: int = db.Column(db.String, nullable=False)
    linename: str = db.Column(db.String, nullable=False)
    point = db.Column(Geometry('POINT'))

这是我的棉花糖架构,

    class LocationsSchema(SQLAlchemyAutoSchema):
        point = fields.Method('wkt_to_geojson')

        def wkt_to_geojson(self, obj):
            return {'type': 'Feature', 'properties': {'linename': obj.linename}, 'geometry': shapely.geometry.mapping(to_shape(obj.point))}

        class Meta:
            model = Locations

locations_schema = LocationsSchema(many=True, only=["point"])

这是我的蓝图路线:

@map_data_blueprint.route('/locations', methods=['GET'])
def all_items():
    locations = Locations.query.all()

    serialized = locations_schema.dump(locations)
    return jsonify(serialized)

这是我从 API 收到的 json:

[
  {
    "id": 2, 
    "point": {
      "geometry": {
        "coordinates": [
          6.130649, 
          49.609332
        ], 
        "type": "Point"
      }, 
      "properties": {
        "linename": "1"
      }, 
      "type": "Feature"
    }
  }, 
  {
    "id": 3, 
    "point": {
      "geometry": {
        "coordinates": [
          6.126288, 
          49.598557
        ], 
        "type": "Point"
      }, 
      "properties": {
        "linename": "1"
      }, 
      "type": "Feature"
    }
  }] 
  

但我正在尝试获取FeatureCollection Geojson 格式,这是一个示例here

【问题讨论】:

    标签: flask-sqlalchemy geojson shapely marshmallow-sqlalchemy


    【解决方案1】:

    我通过结合 geoalchemy2.shape、shapely 和 geojson 包找到了一个解决方案。我删除了这个特定 API 的棉花糖层,因为我没有找到棉花糖层的方法。

    def parse_geojson(obj):
        geo = shapely.geometry.mapping(to_shape(obj.point))
        if geo:
            return geojson.Feature(
                id=obj.id,
                geometry=geo,
                properties={
                    "linename": obj.linename
                })
    
    @map_data_blueprint.route('/locations', methods=['GET'])
    def all_items():
        locations = Locations.query.all()  
        features = [parse_geojson(location) for location in locations]
        serialized = geojson.dumps(geojson.FeatureCollection(features))
        return serialized
    

    我不知道在路由中序列化查询答案是否是最佳做法,但这可行。

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多