Within the database, geometries are stored on disk in a format only used by the PostGIS program. In order for external programs to insert and retrieve useful geometries, they need to be converted into a format that other applications can understand. Fortunately, PostGIS supports emitting and consuming geometries in a large number of formats:
from Introduction to PostGIS
With the WKB format:
Well-known binary (WKB):
ST_GeomFromWKB(bytea) returns geometry
ST_AsBinary(geometry) returns bytea
ST_AsEWKB(geometry) returns bytea
ogr recognize geometries an not a bytea result (ST_AsEWKB())
# result -> bytea format:
query = "SELECT ST_AsEWKB(geom) FROM points LIMIT 1"
# result -> geometry from bytea:
query = "SELECT ST_GeomFromWKB(ST_AsEWKB(geom)) from points LIMIT 1;"
Test with one of my tables:
nothing:
query = """SELECT ST_AsText(ST_AsEWKB(geom)) from mytable;"""
cur = conn.cursor()
cur.execute(query)
row = cur.fetchone()
print row[0]
'01010000208A7A0000DD2571661A9B10410CCD751AEBF70241'
and a geometry:
query = """SELECT ST_AsText(ST_GeomFromWKB(ST_AsEWKB(geom))) from mytable;"""
# result
cur.execute(query)
row = cur.fetchone()
print row
('POINT(272070.600041 155389.38792)',)
So, let's try:
query = """SELECT ST_AsText(ST_GeomFromWKB(ST_AsEWKB(geom))) from mytable;"""
cur = conn.cursor()
cur.execute(query)
row = cur.fetchone()
wkb = row[0];
geom = ogr.CreateGeometryFromWkb(wkb)
ERROR 3: OGR Error: Unsupported geometry type
Why ?
Because the result of the query is a string:
'01010000208A7A0000DD2571661A9B10410CCD751AEBF70241'
and not a bytecode.
You need to decode this string (look at Create Geometry from WKB in the Python GDAL/OGR Cookbook ).
That is why it is much easier to use:
1) other output formats (WKT, GeoJSON, ...)
query = """SELECT ST_AsGeoJSON(geom) from mytable;"""
cur.execute(query)
row = cur.fetchone()
point = ogr.CreateGeometryFromJson(row[0])
print "%d,%d" % (point.GetX(), point.GetY())
272070,155389
2) directly osgeo.ogr (How to convert PostGIS table to Shapefile in Python?, for example)
geom = org.CreateGeometryFromWkb(wkb)(should beogrnotorg). – Arthur Mar 11 '14 at 16:41