项目作者: tilery

项目描述 :
PostGIS helpers for psycopg2 and asyncpg
高级语言: Python
项目地址: git://github.com/tilery/python-postgis.git
创建时间: 2015-11-24T16:40:04Z
项目社区:https://github.com/tilery/python-postgis

开源协议:

下载


Circle CI PyPI PyPI PyPI PyPI

python-postgis

PostGIS helpers for psycopg2 and asyncpg.

Install

  1. pip install postgis

If you want a compiled version, first install cython:

  1. pip install cython
  2. pip install postgis

Usage

You need to register the extension:

  1. # With psycopg2
  2. > from postgis.psycopg import register
  3. > register(connection)
  4. # With asyncpg
  5. > from postgis.asyncpg import register
  6. > await register(connection)

Then you can pass python geometries instance to psycopg:

  1. > cursor.execute('INSERT INTO table (geom) VALUES (%s)', [Point(x=1, y=2, srid=4326)])

And retrieve data as python geometries instances:

  1. > cursor.execute('SELECT geom FROM points LIMIT 1')
  2. > geom = cursor.fetchone()[0]
  3. > geom
  4. <Point POINT(1.0 2.0)>

Example with psycopg2

  1. > import psycopg2
  2. > from postgis import LineString
  3. > from postgis.psycopg import register
  4. > db = psycopg2.connect(dbname="test")
  5. > register(db)
  6. > cursor = db.cursor()
  7. > cursor.execute('CREATE TABLE IF NOT EXISTS mytable ("geom" geometry(LineString) NOT NULL)')
  8. > cursor.execute('INSERT INTO mytable (geom) VALUES (%s)', [LineString([(1, 2), (3, 4)], srid=4326)])
  9. > cursor.execute('SELECT geom FROM mytable LIMIT 1')
  10. > geom = cursor.fetchone()[0]
  11. > geom
  12. <LineString LINESTRING(1.0 2.0, 3.0 4.0)>
  13. > geom[0]
  14. <Point POINT(1.0 2.0)>
  15. > geom.coords
  16. ((1.0, 2.0), (3.0, 4.0))
  17. > geom.geojson
  18. {'coordinates': ((1.0, 2.0), (3.0, 4.0)), 'type': 'LineString'}
  19. > str(geom.geojson)
  20. '{"type": "LineString", "coordinates": [[1, 2], [3, 4]]}'

Example with asyncpg

  1. from postgis.asyncpg import register
  2. pool = await create_pool(**DB_CONFIG, loop=loop, max_size=100,
  3. init=register)