5

私の問題はこれです。一部のデータのモデルを作成しています。

class Cables(Base):
    __tablename__ = 'cables'

    id = Column(Integer, nullable=False)
    route = Column(Geometry(geometry_type='LINESTRING', srid=4326), nullable=False)

今、そのようなルートを GeoJSON に変換したいと思います。

私が試したこと

@app.route("/api/cable/<int:id>", methods=['GET'])
def get_cable(id):
    cable = session.query(Cables).filter(Cables.id == id).first()
    return str(geoalchemy2.functions.ST_AsGeoJSON(cable.route))

戻り値ST_AsGeoJSON(ST_GeomFromEWKB(:ST_GeomFromEWKB_1))

リターンを変更した場合:

return geoalchemy2.functions.ST_AsGeoJSON(cable.route)

戻り値TypeError: 'ST_AsGeoJSON' object is not callable

return str(cable.route)

戻り値0102000020e610000002000000b34fd4d9bca351c032e14d5134c240c0d24f8055e0a351c0dedea9f4dcbf40c0 これは、ジオメトリ オブジェクトがあることを示します。

return cable.route

戻り値TypeError: 'WKBElement' object is not callable

ルートタイプを印刷すると、

print(type(cable.route))

戻り値

<class 'geoalchemy2.elements.WKBElement'>

クラス自体ではなく、そのようなクラスのオブジェクトを返す必要があると思いました。この時点で困惑しており、今何をすべきかわかりません。

助言がありますか?

4

3 に答える 3

4

ST_AsGeoJSON を呼び出す正しい方法はクエリ内にあるようです。例えば、

ruta = session.query(Cables.route.ST_AsGeoJSON()).filter(Cables.id == id).first()

私がやったことは、16進バイト文字列を読み取ってから辞書に変換するために新しいライブラリを(格好良く)インストールすることでした。辞書は簡単な方法でjsonに変換できるからです。

def ewkb_route_to_dict(self):
    """
    returns the cable's route as a dictionary.
    It uses shapely.wkb.loads. The first argument is the route as a bytestring,
    and the second one (True) is to tell loads that
    the input wkb will be represented as a hex string
    """
    return mapping(shapely.wkb.loads(str(self.route), True))

次に、to string メソッドで:

def __str__(self):
    d = dict()
    ...
    d["route"] = self.ewkb_route_to_dict()
    ...
    return dumps(d)

これにより、ジオメトリが GeoJSON に正しく変換されます。

于 2017-01-18T15:37:38.083 に答える
2

この投稿が古いことは知っていますが、まだこの問題を抱えている人のために、私の解決策に従います。

import ast
from flask.json import jsonify
from sqlalchemy import func

@app.route("/api/cable/<int:id>", methods=['GET'])
def get_cable(id):
    geom = session.query(func.ST_AsGeoJSON(Cables.route)).filter(Cables.id == id).scalar()
    # The code below makes a geojson with CRS.
    # See http://www.postgis.org/docs/ST_AsGeoJSON.html for more details.
    #geom = session.query(func.ST_AsGeoJSON(Cables.route,15,2)).filter(Cables.id == id).scalar()
    return jsonify(ast.literal_eval(geom))
于 2018-07-27T17:17:21.643 に答える