如何为GeoJson创建棉花糖SQL模式

问题描述

我正在尝试使用烧瓶,sqlAlchemy,棉花糖和PostGIS创建API,这些API返回GeoJson FeatureCollection。我希望能够使用任何地理对象(点,多边形,...)。

我尝试了很多事情,但从未成功地重新创建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(很多=是,仅= [“点”])

这是我的蓝图路线:

@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": "Feature"
    }
  }] 
  

但是我尝试获取FeatureCollection Geojson格式,这里是一个示例:https://storage.googleapis.com/mapsdevsite/json/google.json

解决方法

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

我不知道在路径中序列化查询答案是否是最佳实践,但这是可行的。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...