postgresql 在Python 3上使用PostGIS

qoefvg9y  于 12个月前  发布在  PostgreSQL
关注(0)|答案(4)|浏览(112)

我使用的是Python 3,需要使用postGIS扩展连接到postGre。我打算用psycopg2驱动程序。
这个PPyGIS是我找到的唯一扩展,但它在python 2.7上工作,而不是3.3.0上。
有人知道3.3.0的解决方案吗?

r1zk6ea1

r1zk6ea11#

如果您没有在客户端(Python)对几何对象做任何花哨的操作,psycopg 2可以使用带有几何访问器的本地数据类型或其他GIS输出格式(如GeoJSON)获取最基本的信息。让服务器(PostgreSQL/PostGIS)来完成这些艰巨的工作。
下面是一个随机的例子,将GeoJSON返回到距离感兴趣点1公里以内的形状:

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)

字符串

vtwuwzda

vtwuwzda2#

您实际上可以使用ShapelyGDAL/OGR,但这两个库都有一长串依赖项。
如果您只有很少的用例,您也可以自己实现一个小的协议,基于super slick pygeoif库,如下例所示

from psycopg2.extensions import register_adapter, AsIs, adapt
from pygeoif.geometry import Point

def adapt_point(pt):
    return AsIs("ST_SetSRID(ST_MakePoint({}, {}), 4326)".format(adapt(pt.x), adapt(pt.y)))

register_adapter(Point, adapt_point)

字符串

6yoyoihd

6yoyoihd3#

由于提出了这个问题,Geopandas软件包添加了

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

字符串
它将从具有几何列的SQL表中检索geodaframe
http://geopandas.org/reference.html#geopandas.GeoDataFrame.from_postgis

afdcj2ne

afdcj2ne4#

最简单的方法是以wkb的形式给予几何图形。有了它,你可以取消所有psycopg2的函数,如execute_values

import psycopg2
from psycopg2.extras import execute_values
from osgeo import ogr

d = [{'id' : 1, 'name' : 'A', 'the_geom': ogr.CreateGeometryFromWkt('POINT({} {})'.format(5.085679, 45.042005)).ExportToWkb()},
{'id' : 2, 'name' : 'B','the_geom': ogr.CreateGeometryFromWkt('POINT({} {})'.format(-1.182751, 46.170237)).ExportToWkb() }]

sql = 'INSERT INTO mon_schema.ma_table (id, name the_geom) VALUES %s'
psycopg2.extras.execute_values(pgCur, sql, d)

字符串

相关问题