2017-10-18 34 views
0

私はShapelyのLineMergeやUnionやPostGIS ST_Unionを使って一緒に結合する必要がある、壊れたルートの線ストリングを持っている状況があります。今PostGISジオメトリタイプをShapelyのジオメトリタイプとしてPythonにインポートするには?

私の考えは、ジオメトリタイプとしてLinestringsをインポートするには格好の良いを使用することです。それらを統合するか、Shapelyを使用してそれらをマージし、データベースの結果テーブルにエクスポートし直します。

しかし、PostGISのデータベースのジオメトリタイプは、意味不明のちょうど束です。以下のような...

01020000020e61000.... 

どのように私は、データベースからの格好の良いを使用してPythonのジオメトリタイプにこれを翻訳し、いくつかの操作を行い、その後、それをデータベースに戻ってエクスポートすることができますか?

現在、これは、そのはちょうど今、データベースからそのGEOMオブジェクトの文字列をインポートし、それがジオメトリタイプではないので、エラーを投げて、私のコードです。

def create_shortest_route_geom(shortest_routes): 
    conn = connect_to_database() 
    cur = conn.cursor() 
    shortest_route_geoms = [] 
    for route in shortest_routes: 
     source = str(int(route[1])) 
     target = str(int(route[2])) 
     query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';' 
     cur.execute(query) 
     total_geom = cur.fetchone() 
     for index, node in enumerate(route): 
      try: 
       source = str(int(node)) 
       target = str(int(route[index + 1])) 
       query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';' 
       cur.execute(query) 
       geom = cur.fetchone() 
       query = "SELECT ST_Union("+str(geom[0])+","+str(total_geom[0])+")" 
       cur.execute(query) 
       total_geom = cur.fetchone() 
      except IndexError: 
       print "Last element" 
     shortest_route_geoms.insert(total_geom) 
    return shortest_route_geoms 

EDIT:HEX値としてI may have found my answer here, looking more into it and will update my question with an answer if I figure this out.

+0

の代わりにプレースホルダを使用してくださいSQLクエリに値を連結した文字列と同様に構成されていることがあります。より読みやすいコードを作成し、引用を手動で処理する必要性を排除し、注射のリスクを軽減します。 –

答えて

1

Shapely already has libraries for this specific problem.

PostGISの格納ジオメトリ。 Shapelyの負荷関数を使用して、hex = Trueのパラメータでこれをロードします。あなたはダンプとこれが機能するためには何度もロードする必要が原因

具体的に...

geom = shapely.wkb.loads(hex_geom[0], hex=True) 

は、PostGISのにST_Unionを使用しないでください。格好の良いはlinemerge

関連する問題