def exportData(shapefile): dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, shapefile.filename)) dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromWkt(shapefile.srs_wkt) driver = ogr.GetDriverByName("ESRI Shapefile") datasource = driver.CreateDataSource(dstFile) layer = datasource.CreateLayer(str(shapefile.filename), dstSpatialRef) for attr in shapefile.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) layer.CreateField(field) srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(4326) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) geomField = utils.calcGeometryField(shapefile.geom_type) for feature in shapefile.feature_set.all(): geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) dstFeature = ogr.Feature(layer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrValue in feature.attributevalue_set.all(): utils.setOGRFeatureAttribute( attrValue.attribute, attrValue.value, dstFeature, shapefile.encoding) layer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(shapefile.filename)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() shutil.rmtree(dstDir) f = FileWrapper(temp) response = HttpResponse(f, content_type="application/zip") response['Content-Disposition'] = \ "attachment; filename=" + shapefileName + ".zip" response['Content-Length'] = temp.tell() temp.seek(0) return response
def exportData(shapefile): dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, shapefile.filename)) dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromWkt(shapefile.srs_wkt) driver = ogr.GetDriverByName("ESRI Shapefile") datasource = driver.CreateDataSource(dstFile) layer = datasource.CreateLayer(str(shapefile.filename), dstSpatialRef) for attr in shapefile.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) layer.CreateField(field) srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(4326) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) geomField = utils.calcGeometryField(shapefile.geom_type) for feature in shapefile.feature_set.all(): geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) dstFeature = ogr.Feature(layer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrValue in feature.attributevalue_set.all(): utils.setOGRFeatureAttribute(attrValue.attribute, attrValue.value, dstFeature, shapefile.encoding) layer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(shapefile.filename)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() shutil.rmtree(dstDir) f = FileWrapper(temp) response = HttpResponse(f, content_type="application/zip") response['Content-Disposition'] = \ "attachment; filename=" + shapefileName + ".zip" response['Content-Length'] = temp.tell() temp.seek(0) return response
def exportMultiLayersData(layers, encoding, EPSG, format): try: dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromEPSG(EPSG) driver = ogr.GetDriverByName(ogrDriver_dic[format]) dstDir = tempfile.mkdtemp() dstFile = str( os.path.join(dstDir, layers[0].name + filenameExt_dic[format])) datasource = driver.CreateDataSource(dstFile) for layer in layers: vlayer = datasource.CreateLayer(str(layer.name), dstSpatialRef) #retrive attributes for attr in layer.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) vlayer.CreateField(field) #save features in shapefile srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(3857) coordTransform = osr.CoordinateTransformation( srcSpatialRef, dstSpatialRef) geomField = utils.calcGeometryField(layer.geom_type) for feature in layer.feature_set.all().order_by('id_relat'): if geometry: geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) else: dstGeometry = None #save attributes in the shapefile dstFeature = ogr.Feature(vlayer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrName, attrValue in feature.attribute_value.iteritems(): attribute = Attribute.objects.get( name=str(attrName), shapefile=feature.shapefile) utils.setOGRFeatureAttribute(attribute, attrValue, dstFeature, encoding) vlayer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() #compress the shapefile temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(layer.name)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() #delete temporary files shutil.rmtree(dstDir) #return the zip to user f = FileWrapper(temp) response = StreamingHttpResponse(f, content_type="application/zip") response[ 'Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[ format] response['Content-Length'] = temp.tell() temp.seek(0) return None, response except BaseException, e: return e.rstrip('\n'), None
def exportMergedData(layers, encoding, EPSG, format): start_time = time.time() try: dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromEPSG(EPSG) driver = ogr.GetDriverByName(ogrDriver_dic[format]) layer_name = '_'.join([layer.name for layer in layers]) + "_merged" attributes = [ attribute for layer in layers for attribute in layer.attribute_set.all() ] features = tuple([ (feature, layer.geom_type) for layer in layers for feature in layer.feature_set.all().order_by('id_relat') ]) if format == "shp": if len({g for f, g in features}) != 1: return "Shapefile format does not support different geometry types in the same layer", None dstDir = tempfile.mkdtemp() dstFile = str( os.path.join(dstDir, layer_name + filenameExt_dic[format])) datasource = driver.CreateDataSource(dstFile) vlayer = datasource.CreateLayer(str(layer.name), dstSpatialRef) #retrive attributes for attr in attributes: field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) fields.append(field) vlayer.CreateField(field) #save features in shapefile srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(3857) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) for feature, geom_type in features: geometry = getattr(feature, utils.calcGeometryField(geom_type)) if geometry: geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) else: dstGeometry = None #save attributes in the shapefile dstFeature = ogr.Feature(vlayer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrName, attrValue in feature.attribute_value.iteritems(): attribute = Attribute.objects.get(name=str(attrName), shapefile=feature.shapefile) utils.setOGRFeatureAttribute(attribute, attrValue, dstFeature, encoding) vlayer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() #compress the shapefile temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(layer_name)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() #delete temporary files shutil.rmtree(dstDir) #return the zip to user f = FileWrapper(temp) response = StreamingHttpResponse(f, content_type="application/zip") response[ 'Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[ format] response['Content-Length'] = temp.tell() temp.seek(0) print("Temps final: --- %s seconds ---" % str(time.time() - start_time)) return None, response except BaseException, e: return e, None
def exportMultiLayersData(layers, encoding, EPSG, format): try: dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromEPSG(EPSG) driver = ogr.GetDriverByName(ogrDriver_dic[format]) dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, layers[0].name+filenameExt_dic[format])) datasource = driver.CreateDataSource(dstFile) for layer in layers: vlayer = datasource.CreateLayer(str(layer.name),dstSpatialRef) #retrive attributes for attr in layer.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) vlayer.CreateField(field) #save features in shapefile srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(3857) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) geomField = utils.calcGeometryField(layer.geom_type) for feature in layer.feature_set.all().order_by('id_relat'): if geometry: geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) else: dstGeometry = None #save attributes in the shapefile dstFeature = ogr.Feature(vlayer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrName, attrValue in feature.attribute_value.iteritems(): attribute = Attribute.objects.get(name=str(attrName), shapefile=feature.shapefile) utils.setOGRFeatureAttribute(attribute, attrValue, dstFeature, encoding) vlayer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() #compress the shapefile temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(layer.name)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() #delete temporary files shutil.rmtree(dstDir) #return the zip to user f = FileWrapper(temp) response = StreamingHttpResponse(f, content_type="application/zip") response['Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[format] response['Content-Length'] = temp.tell() temp.seek(0) return None, response except BaseException, e: return e.rstrip('\n'), None
def exportMergedData(layers, encoding, EPSG, format): start_time = time.time() try: dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromEPSG(EPSG) driver = ogr.GetDriverByName(ogrDriver_dic[format]) layer_name = '_'.join([layer.name for layer in layers])+"_merged" attributes = [attribute for layer in layers for attribute in layer.attribute_set.all()] features = tuple([(feature, layer.geom_type) for layer in layers for feature in layer.feature_set.all().order_by('id_relat')]) if format == "shp": if len({g for f, g in features}) != 1: return "Shapefile format does not support different geometry types in the same layer", None dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, layer_name+filenameExt_dic[format])) datasource = driver.CreateDataSource(dstFile) vlayer = datasource.CreateLayer(str(layer.name),dstSpatialRef) #retrive attributes for attr in attributes: field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) fields.append(field) vlayer.CreateField(field) #save features in shapefile srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(3857) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) for feature, geom_type in features: geometry = getattr(feature, utils.calcGeometryField(geom_type)) if geometry: geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) else: dstGeometry = None #save attributes in the shapefile dstFeature = ogr.Feature(vlayer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrName, attrValue in feature.attribute_value.iteritems(): attribute = Attribute.objects.get(name=str(attrName), shapefile=feature.shapefile) utils.setOGRFeatureAttribute(attribute, attrValue, dstFeature, encoding) vlayer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() #compress the shapefile temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(layer_name)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() #delete temporary files shutil.rmtree(dstDir) #return the zip to user f = FileWrapper(temp) response = StreamingHttpResponse(f, content_type="application/zip") response['Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[format] response['Content-Length'] = temp.tell() temp.seek(0) print("Temps final: --- %s seconds ---" % str(time.time() - start_time)) return None, response except BaseException, e: return e, None
def exportData (shapefile): dstDir = tempfile.mkdtemp () dstFile = str ( os.path.join (dstDir, shapefile.filename) ) dstSpatialRef = osr.SpatialReference () dstSpatialRef.ImportFromWkt ( shapefile.srs_wkd) driver = ogr.GetDriverByName ( "ESRI Shapefile") datasource = driver.CreateDataSource ( dstFile ) layer = datasource.CreateLayer ( str ( shapefile.filename ), dstSpatialRef ) # find the spatial reference srcSpatialRef = osr.SpatialReference () srcSpatialRef.ImportFromEPSG ( 4326 ) coordTransform = osr.CoordinateTransformation ( srcSpatialRef , dstSpatialRef) geomField = utils.calcGeometryField ( shapefile.geom_type ) # Define layer attributes for attr in shapefile.attribute_set.all (): field = ogr.FieldDefn ( str ( attr.name ) , attr.type ) field.SetWidth ( attr.width ) field.SetPrecision ( attr.precision ) layer.CreateField ( field ) # Add all the (Single type) geometries for this layer for feature in shapefile.feature_set.all (): # Geometry is a django construct inherited from GeometryField geometry = getattr ( feature , geomField ) geometry = utils.unwrapGEOSGeometry (geometry) dstGeometry = ogr.CreateGeometryFromWkt ( geometry.wkt ) dstGeometry.Transform ( coordTransform ) dstFeature = ogr.Feature ( layer.GetLayerDefn () ) dstFeature.SetGeometry ( dstGeometry ) # add in the feature's attributes for attrValue in feature.attributevalue_set.all (): utils.setOGRFeatureAttribute ( attrValue.attribute , attrValue.value, dstFeature, shapefile.encoding) layer.CreateFeature ( dstFeature ) dstFeature.Destroy () datasource.Destroy () # Compress the shapefile temp = tempfile.TemporaryFile () zipHandle = zipfile.ZipFile ( temp, 'w' , zipfile.ZIP_DEFLATED ) for fName in os.listdir ( dstDir ): zipHandle.write ( os.path.join ( dstDir , fName ) , fName ) zipHandle.close () # useful links to temp's directory # shapefileBase = os.path.splitext ( dstFile) [0] shapefileName = os.path.splitext ( shapefile.filename)[0] # Delete the temporary files shutil.rmtree ( dstDir ) # Return the zip archive to the user f= FileWrapper ( temp ) response = HttpResponse ( f , content_type="application\zip") response ['Content-Disposition'] = \ "attachment; filename=" + shapefileName + ".zip" response ['Content-Length'] = temp.tell () temp.seek (0) return response
def exportData(shapefile): dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, shapefile.filename)) dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromWkt(shapefile.srs_wkd) driver = ogr.GetDriverByName("ESRI Shapefile") datasource = driver.CreateDataSource(dstFile) layer = datasource.CreateLayer(str(shapefile.filename), dstSpatialRef) # find the spatial reference srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(4326) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) geomField = utils.calcGeometryField(shapefile.geom_type) # Define layer attributes for attr in shapefile.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) layer.CreateField(field) # Add all the (Single type) geometries for this layer for feature in shapefile.feature_set.all(): # Geometry is a django construct inherited from GeometryField geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) dstFeature = ogr.Feature(layer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) # add in the feature's attributes for attrValue in feature.attributevalue_set.all(): utils.setOGRFeatureAttribute(attrValue.attribute, attrValue.value, dstFeature, shapefile.encoding) layer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() # Compress the shapefile temp = tempfile.TemporaryFile() zipHandle = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) for fName in os.listdir(dstDir): zipHandle.write(os.path.join(dstDir, fName), fName) zipHandle.close() # useful links to temp's directory # shapefileBase = os.path.splitext ( dstFile) [0] shapefileName = os.path.splitext(shapefile.filename)[0] # Delete the temporary files shutil.rmtree(dstDir) # Return the zip archive to the user f = FileWrapper(temp) response = HttpResponse(f, content_type="application\zip") response ['Content-Disposition'] = \ "attachment; filename=" + shapefileName + ".zip" response['Content-Length'] = temp.tell() temp.seek(0) return response
def exportData(shapefile): """ Export the contents of the given shapefile. 'shapefile' is the Shapefile object to export. We create a shapefile which holds the contents of the given shapefile, then copy the shapefile into a temporary zip archive. Upon completion, we return a Django HttpResponse object which can be used to send the zipped shapefile to the user's web browser. """ # Create an OGR shapefile to hold the data we're exporting. dstDir = tempfile.mkdtemp() dstFile = str(os.path.join(dstDir, shapefile.filename)) srcSpatialRef = osr.SpatialReference() srcSpatialRef.ImportFromEPSG(4326) dstSpatialRef = osr.SpatialReference() dstSpatialRef.ImportFromWkt(shapefile.srs_wkt) coordTransform = osr.CoordinateTransformation(srcSpatialRef, dstSpatialRef) driver = ogr.GetDriverByName("ESRI Shapefile") datasource = driver.CreateDataSource(dstFile) layer = datasource.CreateLayer(str(shapefile.filename), dstSpatialRef) # Define the various fields which will hold our attributes. for attr in shapefile.attribute_set.all(): field = ogr.FieldDefn(str(attr.name), attr.type) field.SetWidth(attr.width) field.SetPrecision(attr.precision) layer.CreateField(field) # Save the feature geometries and attributes into the shapefile. geomField = utils.calcGeometryField(shapefile.geom_type) for feature in shapefile.feature_set.all(): geometry = getattr(feature, geomField) geometry = utils.unwrapGEOSGeometry(geometry) dstGeometry = ogr.CreateGeometryFromWkt(geometry.wkt) dstGeometry.Transform(coordTransform) dstFeature = ogr.Feature(layer.GetLayerDefn()) dstFeature.SetGeometry(dstGeometry) for attrValue in feature.attributevalue_set.all(): utils.setOGRFeatureAttribute(attrValue.attribute, attrValue.value, dstFeature, shapefile.encoding) layer.CreateFeature(dstFeature) dstFeature.Destroy() datasource.Destroy() # Close the file, write everything to disk. # Compress the shapefile into a ZIP archive. temp = tempfile.TemporaryFile() zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) shapefileBase = os.path.splitext(dstFile)[0] shapefileName = os.path.splitext(shapefile.filename)[0] for fName in os.listdir(dstDir): zip.write(os.path.join(dstDir, fName), fName) zip.close() # Clean up our temporary files. shutil.rmtree(dstDir) # Create an HttpResponse object to send the ZIP file back to the user's web # browser. f = FileWrapper(temp) response = HttpResponse(f, content_type="application/zip") response['Content-Disposition'] = "attachment; filename=" \ + shapefileName + ".zip" response['Content-Length'] = temp.tell() temp.seek(0) return response