plpygis: Python tools for PostGIS
plpygis provides Python tools for working with PostGIS geometries, enabling easy conversion between common formats like WKT, EWKT, WKB, EWKB, and GeoJSON. It focuses on parsing and generating these formats directly in Python, making it suitable for applications interacting with PostGIS. The current version is 0.6.1, and the library maintains an active release cadence with minor updates and bug fixes.
Warnings
- breaking The `wkb` property (e.g., `Point().wkb`) now consistently returns a standard WKB (without SRID metadata). To get an EWKB (which includes SRID metadata), you must now use the `ewkb` property.
- breaking The minimum required Python version has been increased to 3.9.
- breaking For closer adherence to the `__geo_interface__` convention, geometries now represent coordinates and coordinate sequences as tuples instead of lists.
- gotcha When generating WKTs, coordinates default to 6 decimal places of precision. This might lead to unexpected rounding for high-precision data.
- gotcha When parsing LineString or Polygon geometries from WKT, `plpygis` now performs stricter checks to ensure the required number of coordinates are present, raising a `WktError` if not.
Install
-
pip install plpygis
Imports
- Geometry
from plpygis.geometry import Geometry
- Point
from plpygis.geometry import Point
- LineString
from plpygis.geometry import LineString
- Polygon
from plpygis.geometry import Polygon
- from_wkt
from plpygis import from_wkt
from plpygis.wkt import from_wkt
- from_wkb
from plpygis import from_wkb
from plpygis.wkb import from_wkb
Quickstart
from plpygis import Point, LineString
from plpygis.wkt import from_wkt
# Create a Point geometry with an SRID
point = Point(10, 20, srid=4326)
print(f"Point WKT: {point.wkt}")
print(f"Point EWKT: {point.ewkt}")
print(f"Point WKB (hex): {point.wkb.hex()}")
# Create a LineString from EWKT, specifying SRID during parsing
line_ewkt = "SRID=4326;LINESTRING (30 10, 40 20)"
line = from_wkt(line_ewkt, srid=4326) # srid is optional if present in EWKT, but good practice
print(f"LineString GeoJSON: {line.geojson}")
print(f"LineString length: {len(line)}")
# Access properties
print(f"First coordinate of line: {line.geometries[0]}")