python - Using shapely with PostgreSQL -
are there "best practices" of using shapely postgresql?
playing around register_adapter , friends have following code. there better ways?
from psycopg2.extensions import ( adapt, register_adapter, asis, new_type, register_type ) shapely.geometry import point, polygon import numpy 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), ) x, y in [(0, 0), (1, 0), (1, 1), (2, 3), (0, 1)] ] cur.executemany('insert 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)) x, y in pts) return asis("'(%s)'" % inner) register_adapter(polygon, adapt_polygon) def cast_point(value, cur): if value 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 pts pt <@ polygon %s ''', (poly,)) pt, in cur: print(pt, type(pt))
Comments
Post a Comment