Beispiel #1
0
def editFeature(request, shapefile_id, feature_id=None):
    """ Permite al usuario añadir o editar una feature del shapefile.
        el campo 'feature_id' será None if we are adding a new feature.
    """
    shapefile = Shapefile.objects.get(id=shapefile_id)

    if request.method == "POST" and "delete" in request.POST:
        # User clicked on the "Delete" button -> show "Delete Feature" page.
        return HttpResponseRedirect("/deleteFeature/" + shapefile_id + "/" +
                                    feature_id)

    geometryField = utils.calc_geometry_field(shapefile.geom_type)

    formType = shapefileEditor.getMapForm(shapefile)

    if feature_id == None:
        # Annadiendo una nueva feature.
        feature = Feature(shapefile=shapefile)
        attributes = []
    else:
        # Editando una feature.
        feature = Feature.objects.get(id=feature_id)

    # Toma los atributos para esta feature.

    attributes = []
    for attrValue in feature.attributevalue_set.all():
        attributes.append([attrValue.attribute.name, attrValue.value])
    attributes.sort()

    # Muestra el formulario

    if request.method == "GET":
        wkt = getattr(feature, geometryField)
        form = formType({'geometry': wkt})
        return render_to_response("editFeature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
    elif request.method == "POST":
        form = formType(request.POST)
        try:
            if form.is_valid():
                wkt = form.cleaned_data['geometry']
                setattr(feature, geometryField, wkt)
                feature.save()
                # Devuelve al usuario a la pagina de seleccion de features.
                return HttpResponseRedirect("/edit/" + shapefile_id)
        except ValueError:
            pass

        return render_to_response("editFeature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
Beispiel #2
0
def edit_feature(request, shapefile_id, feature_id=None):
    if request.method == "POST" and "delete" in request.POST:
        return HttpResponseRedirect("/delete_feature/" + shapefile_id + "/" +
                                    feature_id)
    try:
        shapefile = Shapefile.objects.get(id=shapefile_id)
    except ShapeFile.DoesNotExist:
        return HttpResponseNotFound()

    if feature_id == None:
        feature = Feature(shapefile=shapefile)
    else:
        try:
            feature = Feature.objects.get(id=feature_id)
        except Feature.DoesNotExist:
            return HttpResponseNotFound()
    attributes = []
    for attr_value in feature.attributevalue_set.all():
        attributes.append([attr_value.attribute.name, attr_value.value])
        attributes.sort()
    if request.method == "GET":
        form = MyForm()
        return render(request, "template.html", {'form': form})
    elif request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            # Extract and save the form's contents here...
            return HttpResponseRedirect("/somewhere/else")
        return render(request, "template.html", {'form': form})
    geometry_field = utils.calc_geometry_field(shapefile.geom_type)
    form_class = utils.get_map_form(shapefile)
    if request.method == "GET":
        wkt = getattr(feature, geometry_field)
        form = form_class({'geometry': wkt})
        return render(request, "edit_feature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
    elif request.method == "POST":
        form = form_class(request.POST)
        try:
            if form.is_valid():
                wkt = form.cleaned_data['geometry']
                setattr(feature, geometry_field, wkt)
                feature.save()
                return HttpResponseRedirect("/edit/" + shapefile_id)
        except ValueError:
            pass
        return render(request, "edit_feature.html", {
            'shapefile': shapefile,
            'form': form,
            'attributes': attributes
        })
Beispiel #3
0
def import_data(shapefile):

    # Extract the uploaded shapefile.

    fd, fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "Not a valid zip archive."

    zip = zipfile.ZipFile(fname)

    required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False

    for info in zip.infolist():
        suffix = os.path.splitext(info.filename)[1].lower()
        if suffix in required_suffixes:
            has_suffix[suffix] = True

    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            zip.close()
            os.remove(fname)
            return "Archive missing required " + suffix + " file."

    shapefile_name = None
    dir_name = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp"):
            shapefile_name = info.filename

        dst_file = os.path.join(dir_name, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    # Open the shapefile.

    try:
        datasource = ogr.Open(os.path.join(dir_name, shapefile_name))
        layer = datasource.GetLayer(0)
        shapefile_ok = True
    except:
        traceback.print_exc()
        shapefile_ok = False

    if not shapefile_ok:
        os.remove(fname)
        shutil.rmtree(dir_name)
        return "Not a valid shapefile."

    # Save Shapefile object to database.

    src_spatial_ref = layer.GetSpatialRef()
    geom_type = layer.GetLayerDefn().GetGeomType()
    geom_name = ogr.GeometryTypeToName(geom_type)
    shapefile = Shapefile(filename=shapefile_name,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geom_name)
    shapefile.save()

    # Define the shapefile's attributes.

    attributes = []
    layer_def = layer.GetLayerDefn()
    for i in range(layer_def.GetFieldCount()):
        field_def = layer_def.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=field_def.GetName(),
                         type=field_def.GetType(),
                         width=field_def.GetWidth(),
                         precision=field_def.GetPrecision())
        attr.save()
        attributes.append(attr)

    # Save the Shapefile's features and attributes to disk.

    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)

    coord_transform = osr.CoordinateTransformation(src_spatial_ref,
                                                   dst_spatial_ref)

    for i in range(layer.GetFeatureCount()):
        src_feature = layer.GetFeature(i)
        src_geometry = src_feature.GetGeometryRef()
        src_geometry.Transform(coord_transform)
        geometry = GEOSGeometry(src_geometry.ExportToWkt())
        geometry = utils.wrap_geos_geometry(geometry)

        geom_field = utils.calc_geometry_field(geom_name)

        fields = {}
        fields['shapefile'] = shapefile
        fields[geom_field] = geometry

        feature = Feature(**fields)
        feature.save()

        for attr in attributes:
            success, result = utils.get_ogr_feature_attribute(
                attr, src_feature)
            if not success:
                os.remove(fname)
                shutil.rmtree(dir_name)
                shapefile.delete()
                return result

            attr_value = AttributeValue(feature=feature,
                                        attribute=attr,
                                        value=result)
            attr_value.save()

    os.remove(fname)
    shutil.rmtree(dir_name)
    return None
Beispiel #4
0
def import_data(shapefile):
    # Copia el archivo zip en un archivo temporal

    fd,fname = tempfile.mkstemp(suffix=".zip")
    os.close(fd)

    f = open(fname, "wb")
    for chunk in shapefile.chunks():
        f.write(chunk)
    f.close()

    # Se abre el zip y se chequea su contenido.

    if not zipfile.is_zipfile(fname):
        os.remove(fname)
        return "No es un archivo zip válido."

    zip = zipfile.ZipFile(fname)
    
    #Diferenciacion de los archivos requeridos segun el formato del archivo de entrada

    es_shp = False
    for info in zip.infolist():
        extension = os.path.splitext(info.filename)[1].lower()
        if extension == '.shp':
            es_shp = True
    
    #Sie s un shp, se aplica una comprobación de que todos los archivos necearios estén en el zip
    if es_shp: 
        required_suffixes = [".shp", ".shx", ".dbf", ".prj"]
        hasSuffix = {}
        for suffix in required_suffixes:
            hasSuffix[suffix] = False
    
        for info in zip.infolist():
            extension = os.path.splitext(info.filename)[1].lower()
            if extension in required_suffixes:
                hasSuffix[extension] = True
            else:
                print "Archivo extraño: " + info.filename
    
        for suffix in required_suffixes:
            if not hasSuffix[suffix]:
                zip.close()
                os.remove(fname)
                return "No se encuentra el archivo " + suffix + " requerido"
            
    else:
        zip.close()
    
    # Descomprime el zip en un directorio temporal.
    # Se toma el nombre del archivo principal.
        
    zip = zipfile.ZipFile(fname)
    shapefileName = None
    dirname = tempfile.mkdtemp()
    for info in zip.infolist():
        if info.filename.endswith(".shp") and es_shp:
            shapefileName = info.filename
        if not es_shp:
            shapefileName = info.filename
            
        dst_file = os.path.join(dirname, info.filename)
        f = open(dst_file, "wb")
        f.write(zip.read(info.filename))
        f.close()
    zip.close()

    # Intenta abrir el archivo

    try:
        datasource  = ogr.Open(os.path.join(dirname, shapefileName))
        layer       = datasource.GetLayer(0)
        shapefileOK = True
    except:
        traceback.print_exc()
        shapefileOK = False

    if not shapefileOK:
        os.remove(fname)
        shutil.rmtree(dirname)
        return "No es un archivo válido."

    # Importar los datos del shapefile abierto.
    
    feature1 = layer.GetFeature(0)
    tipo_geometria = feature1.geometry().GetGeometryType()
    feature1.Destroy()
    #geometryType  = layer.GetLayerDefn().GetGeomType()
    geometryName = ogr.GeometryTypeToName(tipo_geometria)
    geometryName = geometryName.replace(" ", "")
    src_spatial_ref = layer.GetSpatialRef()
    dst_spatial_ref = osr.SpatialReference()
    dst_spatial_ref.ImportFromEPSG(4326)         #Aqui se define que sistema de coordenadas se le asigna en la BD

    shapefile = Shapefile(filename=shapefileName,
                          srs_wkt=src_spatial_ref.ExportToWkt(),
                          geom_type=geometryName)
    shapefile.save()

    attributes = []
    layerDef = layer.GetLayerDefn()
    for i in range(layerDef.GetFieldCount()):
        fieldDef = layerDef.GetFieldDefn(i)
        attr = Attribute(shapefile=shapefile,
                         name=fieldDef.GetName(),
                         type=fieldDef.GetType(),
                         width=fieldDef.GetWidth(),
                         precision=fieldDef.GetPrecision())
        attr.save()
        attributes.append(attr)
    #layerDef.Destroy()    
    
    coordTransform = osr.CoordinateTransformation(src_spatial_ref,
                                                  dst_spatial_ref)
        
    for i in range(layer.GetFeatureCount()):
        srcFeature = layer.GetFeature(i)
        srcGeometry = srcFeature.GetGeometryRef()
        srcGeometry.Transform(coordTransform)
        geometry = GEOSGeometry(srcGeometry.ExportToWkt())
        geometry = utils.wrap_geos_geometry(geometry)
        geometryField = utils.calc_geometry_field(geometryName)
        args = {}
        args['shapefile'] = shapefile
        args[geometryField] = geometry
        feature = Feature(**args)
        feature.save()
        
        for attr in attributes:
            success,result = utils.get_ogr_feature_attribute(attr, srcFeature)
            #if not success:
                #os.remove(fname)
                #print dirname
                #shutil.rmtree(dirname)
                #shapefile.delete()
                #return result
            if success:
                attrValue = AttributeValue(feature=feature, attribute=attr, value=result)
                attrValue.save()
        
    # Finalmente, limpiarlo todo.
    datasource.Destroy()
    os.remove(fname)
    print dirname
    shutil.rmtree(dirname)

    return None # Exito.