Using PostGIS on Python 3

Mille Bii picture Mille Bii · Feb 18, 2013 · Viewed 9.6k times · Source

I'm using Python 3 and need to connect to postGre with postGIS extensions. I'm intending to use a psycopg2 driver.
This PPyGIS is the only extension I found, but it works on python 2.7 not 3.3.0.
Any one knows a solution working on 3.3.0 ?

Answer

Mike T picture Mike T · Feb 18, 2013

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 psycopg2
conn = psycopg2.connect(database='postgis', user='postgres')
curs = conn.cursor()

# Find the distance within 1 km of point-of-interest
poi = (-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 f
WHERE ST_DWithin(geog, poi, 1000);""", poi)

for row in curs.fetchall():
    print(row)