Using PostGIS on Python 3 Using PostGIS on Python 3 python python

Using PostGIS on Python 3


If you are not doing anything fancy with the geometry objects on the client side (Python), psycopg2 can get most basic info using native data types with geometry accessors, or other GIS output formats like GeoJSON. Let the server (PostgreSQL/PostGIS) do the hard work.

Here is a random example to return the GeoJSON to shapes that are within 1 km of a point of interest:

import psycopg2conn = psycopg2.connect(database='postgis', user='postgres')curs = conn.cursor()# Find the distance within 1 km of point-of-interestpoi = (-124.3, 53.2)  # longitude, latitude# Table 'my_points' has a geography column 'geog'curs.execute("""\SELECT gid, ST_AsGeoJSON(geog), ST_Distance(geog, poi)FROM my_points, (SELECT ST_MakePoint(%s, %s)::geography AS poi) AS fWHERE ST_DWithin(geog, poi, 1000);""", poi)for row in curs.fetchall():    print(row)


You may actually use Shapely or GDAL/OGR, but both libraries have a long list of dependencies.

If you have only very few usecases, you might also implement a small protocol yourself, based on the super slick pygeoif library, like the example below

from psycopg2.extensions import register_adapter, AsIs, adaptfrom pygeoif.geometry import Pointdef adapt_point(pt):    return AsIs("ST_SetSRID(ST_MakePoint({}, {}), 4326)".format(adapt(pt.x), adapt(pt.y)))register_adapter(Point, adapt_point)


Since this question was asked the Geopandas package added

classmethod GeoDataFrame.from_postgis(sql, con, geom_col='geom',     crs=None, index_col=None, coerce_float=True, parse_dates=None, params=None)

which will retrieve a geodataframe from a sql table with a geometry column

http://geopandas.org/reference.html#geopandas.GeoDataFrame.from_postgis