1

Is there a way to use Fiona instead of OGR to convert a GDB over to postgresql / postgis within Python? If so, how or where can I look? I cannot seem to find this within the Fiona site or by simply Googling around.

2
  • Does this not answer the question -- ie, using gdal from Fiona? Commented Jul 30, 2016 at 6:40
  • @John Barça I'm not sure I follow you. I can open up a file via Fiona. I can parse through layers using Fiona. What I'm not certain of is a graceful way to CONVERT things to postgresql / postgis. I'm trying to remove OGR calls within Python to be strictly done via Fiona (or so I thought). Can this be done? I thought it should be since Fiona is based off of OGR. Commented Aug 1, 2016 at 16:57

2 Answers 2

2

Fiona does not currently connect to PostgreSQL/PostGIS as shown here, and sort-of documented here.

OGR is still a useful tool for PostgreSQL/PostGIS, and other spatial databases.

2
  • Thanks... I wasn't looking to connect... just convert... but maybe you're saying connecting is part of the conversion process? I was just trying to utilize Fiona as much as possible since it's simply an OGR package for Python. Commented Aug 18, 2016 at 14:31
  • Yes, you must connect to a data source to do anything. In other words, Fiona (at present) does not work with PostGIS, as it is a subset of the functionality provided by OGR. Commented Aug 18, 2016 at 21:14
1

Fiona works with GeoJSON and postgis can produce GeoJSON geometries with ST_AsGeoJSON(wkbgeometry) which you can wrap with other (non-geometry) properties to produce a FeatureCollection. I just figured that out for postgis use with rasterstats. You can do ST_GeomFromGeoJSON() to go the other way.

No OGR needed because you can do this with a plain vanilla database connection (e.g. psycopg2 in python).

Code snippet:

conn = psycopg2.connect(connString)
if not conn:
    print("No connection established")
    sys.exit(1)

curs = conn.cursor()

sql = """SELECT id, ST_Area(wkb_geometry), ST_Perimeter(wkb_geometry), ST_AsGeoJSON(wkb_geometry)::json 
from spatial_db_table
"""

curs.execute(sql)

features = { "type": "FeatureCollection", 
  "features": [{"type": "feature", "geometry": f[3], "properties": {"id": int(f[0]), "area": float(f[1]), "perimeter": float(f[2])}} for f in curs.fetchall()]} 

with rasterio.open('my_raster.tif') as src:
        affine = src.transform
        array = src.read(1)

zs = zonal_stats(features, array, affine=affine, stats=["count", "mean", "std", "min", "max", "percentile_25", "percentile_50", "percentile_75"], prefix="", nodata=0, geojson_out=True)

print(zs)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.