0

我正在尝试创建一个使用API烧瓶SQLAlchemy,,,返回Marshmallow。我希望能够使用任何地理对象(、、...)。PostGISGeoJson FeatureCollectionPointPolygone

我尝试了很多东西,但从未成功地重新创建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是一个例子。

4

1 回答 1

0

我通过结合 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

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

于 2020-11-01T09:02:14.193 回答