Python 与PostgreSQL一起使用shapely
是否有与PostgreSQL一起使用shapely的最佳实践 和朋友们一起玩我有以下代码。还有更好的办法吗Python 与PostgreSQL一起使用shapely,python,postgresql,gis,psycopg2,shapely,Python,Postgresql,Gis,Psycopg2,Shapely,是否有与PostgreSQL一起使用shapely的最佳实践 和朋友们一起玩我有以下代码。还有更好的办法吗 from psycopg2.extensions import ( adapt, register_adapter, AsIs, new_type, register_type ) from shapely.geometry import Point, Polygon import numpy as np import psycopg2 conn = psycopg2.conne
from psycopg2.extensions import (
adapt, register_adapter, AsIs, new_type, register_type
)
from shapely.geometry import Point, Polygon
import numpy as np
import psycopg2
conn = psycopg2.connect(host='localhost', user='postgres')
cur = conn.cursor()
cur.execute('CREATE TABLE pts (pt POINT)')
conn.commit()
def quote(v):
return adapt(v).getquoted().decode()
def adapt_point(pt):
x, y = quote(pt.x), quote(pt.y)
return AsIs("'(%s, %s)'" % (x, y))
register_adapter(Point, adapt_point)
points = [
(Point(x, y), )
for x, y in
[(0, 0), (1, 0), (1, 1), (2, 3), (0, 1)]
]
cur.executemany('INSERT INTO pts (pt) VALUES (%s)', points)
conn.commit()
def adapt_polygon(poly):
pts = np.stack(poly.exterior.xy).T
inner = ', '.join('(%s, %s)' % (quote(x), quote(y)) for x, y in pts)
return AsIs("'(%s)'" % inner)
register_adapter(Polygon, adapt_polygon)
def cast_point(value, cur):
if value is None:
return None
# '(2.7,3.6)'
try:
x, y = value[1:-1].split(',')
except ValueError:
raise psycopg2.InterfaceError('bad point representation: %r' % value)
return Point(float(x), float(y))
cur.execute('SELECT NULL::point')
point_oid = cur.description[0].type_code
POINT = new_type((point_oid,), 'POINT', cast_point)
register_type(POINT)
poly = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
cur.execute('''
SELECT pt
FROM pts
WHERE
pt <@ polygon %s
''', (poly,))
for pt, in cur:
print(pt, type(pt))
您可以直接在PostGIS中插入和提取WKT和WKB。同样,您可以使用Shapely的wkt和wkb模块以及附带的加载和转储方法来来回传输几何体。使用Shapely,您应该直接使用wkt和wkb表示。如果您使用的是register_adapter,并且希望手动完成,那么无需安装Shapely,因为它有点重,并且具有依赖性,您可以直接使用pygeoif提供的非常薄的几何对象