【问题标题】:Return valid GeoJSON with Flask + GeoAlchemy2 app使用 Flask + GeoAlchemy2 应用程序返回有效的 GeoJSON
【发布时间】:2020-06-30 20:39:32
【问题描述】:

几天以来,我一直在想如何让我的 Flask 应用返回有效的 GeoJSON,以下是我目前得到的结果:

models.py

class Building(base):

    __tablename__ = 'buildings'

    id = Column(Integer, primary_key=True)
    district = Column(Unicode)
    address = Column(Unicode)
    name = Column(Unicode)
    building_type = Column(Unicode)
    mpoly = Column(Geometry('MULTIPOLYGON'))

    building = relationship("User")


# this part is done as answered here: https://stackoverflow.com/questions/41684512/cant-transform-geometry-to-geojson
    def building_to_dict(self):
        return mapping(shapely.wkb.loads(str(self.mpoly), True))
    
    def __str__(self):
        d = dict()
        d["id"] = self.id
        d["district"] = self.district
        d["address"] = self.address
        d["name"] = self.name
        d["building_type"] = self.building_type
        d["mpoly"] = self.building_to_dict()
        return shapely.dumps(d)

现在在主文件中我有以下路由:

app.py

@app.route('/geojson')
def get_json():
    features = session.query(Building.mpoly.ST_AsGeoJSON()).all()
    return jsonify(features)

这是我的两个问题:

1) 返回类似于 JSON 的响应,如下所示: "{\"type\":\"MultiPolygon\",\"coordinates\":[[[[16.8933137,52.471446],...,]]]}" 不是正确的 GeoJSON。 jsonify 之前的特征变量看起来是这样的: [('{"type":"MultiPolygon","coordinates":[[[[16.914159616,52.473822807],...,]]]}',)]

2) 我的 GeoAlchemy 查询应该是什么样子,不仅返回几何字段,还返回其他字段?

任何形式的提示或帮助都非常感谢,在此先感谢!

【问题讨论】:

  • 所以我不知道确切的解决方案,但我认为您的问题与以下链接有关。 (1)stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify。 (2)stackoverflow.com/questions/7102754/…。根据 1 flask jsonify 中的评论“......不会将 SQLAlchemy 对象和列表转换为 JSON。”所以我相信你可能需要做的是编写一个序列化数据库对象(特征)的函数或类,然后将它传递给返回 jsonify(特征)。
  • [('{"type":"MultiPolygon","coordinates":[[[[16.914159616,52.473822807],...,]]]}',)]

标签: json python-3.x flask flask-sqlalchemy geoalchemy2


【解决方案1】:

您可以使用 marshmallow-sqlalchemy 创建类似 json 的响应。

创建 schemas.py

    #!schemas.py
    from marshmallow import fields
    from marshmallow_sqlalchemy import ModelSchema
    from app.models import Building
    from geoalchemy.shape import to_shape


    class BuildingSchema(ModelSchema):
        id = fields.Integer()
        district = fileds.Unicode()
        address = fileds.Unicode()
        name = fields.Unicode()
        building_type = fields.Unicode()
        mpoly = fileds.Method("geom_to_json")
    
        @staticmethod
        def geom_to_json(obj):
            mpoly = to_shape(obj.mpoly)
            return {
                    lat: mpoly.y,
                    lon: mpoly.x,
                    #and so on ... 
                    } 
        
        class Meta:
            model = Building
            exclude = ("mpoly")
            

    bulding_schema = BuildingSchema(many=True)
    

之后你可以在你的视图(路由)中使用它

    from app.schemas import building_schema 


    @app.route('/geojson')
    def json():
        buildings = Buildings.query.all()
        response = building_schema.dumps(buildings)
        
        return response

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2015-12-23
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多