user1111652 user1111652 - 3 months ago 28
Python Question

Representing Coordinates in GeoAlchemy2

To extend my restfull api with GPS locations I decided to try geoalchemy. I already have a database going and I think it saves the points to my database already. However, everytime I try to print a point that I saved (for instance to return to the the user) I get a memory adress or something like this:

<WKBElement at 0x7ffad5310110; '0101000000fe47a643a7f3494049f4328ae5d61140'>

This is pretty useless for the non initiated programmer nor for a user.

I have a simple question. How do I represent a Geometry object in a human readable form like:

POINT(40.5563 30.5567)


That would be in the Well-Known Binary format; you can use the geoalchemy2.functions.ST_AsText to convert them to the WKT text format.

This would work in the database itself, thus you'd apply this to your query to ask for the results in WKT instead of WKB; that is in your SQLAlchemy you select




For off-database conversions between WKT and WKB, you can use the shapely module. Note that the wkb functions need binary, not hex:

from shapely import wkb, wkt
from binascii import unhexlify
>>> binary = unhexlify(b'0101000000fe47a643a7f3494049f4328ae5d61140')
>>> binary
>>> point = wkb.loads(binary)
>>> point.x, point.y
(51.903542, 4.45986)
>>> wkt.dumps(point)
'POINT (51.9035420000000016 4.4598599999999999)'