Flask uploading shapefiles into postgis

764 Views Asked by At

I am trying to upload a shapefile into PostGIS. I am using Flask and have gotten the files from the user (.shp, .shx, .dbf and .prj) and saved them to temporary files before using PYSHP python library to access the shapes collection.

r = shapefile.Reader(tempfile_name + '.shp')
shapes = r.shapes()

What I want to do is combine the polygons in the shapes collection and add them to the database along with some other data as one record. Basically merging the polygons into a multipolygon. The relevant column of the PostGIS table is defined as:

footprint = db.Column(Geometry(geometry_type='MULTIPOLYGON', srid=27700))

I do not know how to proceed with the merging of the polygons and converting them to a format that can be written to the PostGIS database using SQLAlchemy and GeoAlchemy2. Advice on how to proceed would be gratefully received.

I have looked at geopandas and shapely but can seem to find the relevant information

I am using

  • Flask 1.0.2
  • Postgresql 9.6
  • SQLAlchmey 1.2.7
  • Geoalchemy2 0.4.2

Update 1.

Found a solution that seems to work, but it seems rather messy.

I loop through the shapes() of the shapefile.Reader and save each polygon to an array, before using cascaded_union of shapely library. Then use pygeoif library to convert the information to be saved in the postgis database.

poly = []
for shp in r.shapes():
  if shp.shapeType == 5:
    poly.append(shape(shp.__geo_interface__))
footprint_poly = cascaded_union(poly)

gshape = pygeoif.MultiPolygon(pygeoif.geometry.as_shape(footprint_poly))
project.footprint = 'SRID=27700;{0}'.format(gshape.wkt)
0

There are 0 best solutions below