13

I have a geoalchemy2.elements.WKBElement that comes from a query on a Postgres/PostGIS view. I want to convert this to WKT, or otherwise encode it so that it is (Geo)JSON serialisable. How can I accomplish this?

Assuming similarity to shapely, I thought that geoalchemy2.elements.WKBElement would have a wkt property or class method, but it does not. The __str__ method returns the binascii.hexlify representation of the WKB. In the source for the geoalchemy2.elements there appears to be little else to use.

I'm about to build GDAL with python bindings to attempt to read the WKB and then output as WKT, but this feels like more work than I expected.

1 Answer 1

27

GeoAlchemy supports the PostGIS functions ST_AsText and ST_AsGeoJSON. You can use these in your query to return a WKT/GeoJSON string from the database instead of the WKBElement itself.

from geoalchemy2 import functions

# ...

wkt_qry = session.query(functions.ST_AsText(YourTable.geom))
geojson_qry = session.query(functions.ST_AsGeoJSON(YourTable.geom))

# ...

In fact, since the return type from these functions is just a string, you can also use the SQLAlchemy func object.


If you need to store the WKBElement and get the WKT representation or other attributes at a later time you can use GeoAlchemy's shape module to convert the WKBElement to a Shapely geometry.

from geoalchemy2.shape import to_shape   

# Return a WKBElement instance of your first geometry
wkb_elem = session.query(YourTable.geom).filter(YourTable.id==1).scalar()

# Convert to Shapely geometry
shply_geom = to_shape(wkb_elem)

# Print WKT representation
print shply_geom.wkt
5
  • 1
    Easier than I thought! Thanks. To combine this with a SELECT * construct, I did session.query(Table, functions.ST_AsGeoJSON(Table.geom).label("geojson_geom")). Mar 23, 2017 at 22:04
  • 1
    Just to be clear; using the session object like this means that the work is being done in the database server with a call to PostGIS ST_AsText. It's not happening in the Python code. Is there any way to do anything with the WKB blogs you get from GeoAlchemy2 without going to the database?
    – Nelson
    Oct 21, 2017 at 19:02
  • 4
    @Nelson Yes, this utilises PostGIS functions in the database. I've updated my original answer to include an alternative approach for cases where you do want to get the WKBElement from the database and interrogate it later.
    – Ali
    Oct 23, 2017 at 8:41
  • 2
    It is now simply .wkt property.
    – hyperknot
    Aug 29, 2019 at 13:05
  • Is it possible to do the same but with rows containing a WKBElement? (or maybe I should write the SQL request myself?)
    – cglacet
    May 13, 2020 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.