Skip to content

Instantly share code, notes, and snippets.

@aidos
Last active September 15, 2015 16:30
Show Gist options
  • Save aidos/a2ecad29cd71475a17f9 to your computer and use it in GitHub Desktop.
Save aidos/a2ecad29cd71475a17f9 to your computer and use it in GitHub Desktop.
Using Shapley types with geoalchemy2 / sqlalchemy
import binascii
import sqlalchemy.types
import geoalchemy2.types
from geoalchemy2.shape import WKTElement
import shapely.wkb
import shapely.geometry
class ShapelyGeo(sqlalchemy.types.TypeDecorator):
"""Geometry that speaks in Shapely objects"""
impl = geoalchemy2.types.Geometry
def result_processor(self, dialect, coltype):
def process(value):
if value is not None:
return shapely.wkb.loads(binascii.a2b_hex(value))
return process
def bind_processor(self, dialect):
def process(bindvalue):
if isinstance(bindvalue, WKTElement):
return 'SRID=%d;%s' % (bindvalue.srid, bindvalue.data)
if isinstance(bindvalue, shapely.geometry.base.BaseGeometry):
return bindvalue.to_wkt()
else:
return bindvalue
return process
def an_example():
class Shape(Base):
id = Column(Integer, primary_key=True)
lines = Column(ShapelyGeo('LINESTRING'))
points_on_line = [(0, 0), (10,343), (323,34)]
s = Shape(lines=shapely.geometry.LineString(points_on_line))
session.add(s)
session.commit()
session.expunge_all()
s = session.query(Shape).order_by(Shape.id.desc()).first()
type(s.lines) # shapely.geometry.linestring.LineString
list(s.lines.coords) # [(0, 0), (10,343), (323,34)]
@aidos
Copy link
Author

aidos commented Sep 15, 2015

I couldn't find a simple example of extending geoalchemy2 to use shapley types anywhere. This seems to work ok for me.

ps: I haven't tested the example code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment