当前位置: 首页>>代码示例>>Python>>正文


Python QgsVectorLayerImport.importLayer方法代码示例

本文整理汇总了Python中qgis.core.QgsVectorLayerImport.importLayer方法的典型用法代码示例。如果您正苦于以下问题:Python QgsVectorLayerImport.importLayer方法的具体用法?Python QgsVectorLayerImport.importLayer怎么用?Python QgsVectorLayerImport.importLayer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在qgis.core.QgsVectorLayerImport的用法示例。


在下文中一共展示了QgsVectorLayerImport.importLayer方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: processAlgorithm

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
    def processAlgorithm(self, progress):
        connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)]
        db = postgis.GeoDB.from_name(connection)

        schema = self.getParameterValue(self.SCHEMA)
        overwrite = self.getParameterValue(self.OVERWRITE)
        createIndex = self.getParameterValue(self.CREATEINDEX)
        convertLowerCase = self.getParameterValue(self.LOWERCASE_NAMES)
        dropStringLength = self.getParameterValue(self.DROP_STRING_LENGTH)
        forceSinglePart = self.getParameterValue(self.FORCE_SINGLEPART)
        primaryKeyField = self.getParameterValue(self.PRIMARY_KEY) or "id"
        encoding = self.getParameterValue(self.ENCODING)

        layerUri = self.getParameterValue(self.INPUT)
        layer = dataobjects.getObjectFromUri(layerUri)

        table = self.getParameterValue(self.TABLENAME)
        if table:
            table.strip()
        if not table or table == "":
            table = layer.name()
            table = table.replace(".", "_")
        table = table.replace(" ", "").lower()[0:62]
        providerName = "postgres"

        geomColumn = self.getParameterValue(self.GEOMETRY_COLUMN)
        if not geomColumn:
            geomColumn = "the_geom"

        options = {}
        if overwrite:
            options["overwrite"] = True
        if convertLowerCase:
            options["lowercaseFieldNames"] = True
            geomColumn = geomColumn.lower()
        if dropStringLength:
            options["dropStringConstraints"] = True
        if forceSinglePart:
            options["forceSinglePartGeometryType"] = True

        # Clear geometry column for non-geometry tables
        if not layer.hasGeometryType():
            geomColumn = None

        uri = db.uri
        uri.setDataSource(schema, table, geomColumn, "", primaryKeyField)

        if encoding:
            layer.setProviderEncoding(encoding)

        (ret, errMsg) = QgsVectorLayerImport.importLayer(
            layer, uri.uri(), providerName, self.crs, False, False, options
        )
        if ret != 0:
            raise GeoAlgorithmExecutionException(self.tr("Error importing to PostGIS\n%s" % errMsg))

        if geomColumn and createIndex:
            db.create_spatial_index(table, schema, geomColumn)

        db.vacuum_analyze(table, schema)
开发者ID:qgis,项目名称:QGIS,代码行数:62,代码来源:ImportIntoPostGIS.py

示例2: testKey

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
 def testKey(lyr, key, kfnames):
     self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.import_test')
     uri = '%s table="qgis_test"."import_test" (g)' % self.dbconn
     if key is not None:
         uri += ' key=\'%s\'' % key
     err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs())
     self.assertEqual(err[0], QgsVectorLayerImport.NoError,
                      'unexpected import error {0}'.format(err))
     olyr = QgsVectorLayer(uri, "y", "postgres")
     self.assertTrue(olyr.isValid())
     flds = lyr.fields()
     oflds = olyr.fields()
     if key is None:
         # if the pkey was not given, it will create a pkey
         self.assertEquals(oflds.size(), flds.size() + 1)
         self.assertEquals(oflds[0].name(), kfnames[0])
         for i in range(flds.size()):
             self.assertEqual(oflds[i + 1].name(), flds[i].name())
     else:
         # pkey was given, no extra field generated
         self.assertEquals(oflds.size(), flds.size())
         for i in range(oflds.size()):
             self.assertEqual(oflds[i].name(), flds[i].name())
     pks = olyr.pkAttributeList()
     self.assertEquals(len(pks), len(kfnames))
     for i in range(0, len(kfnames)):
         self.assertEqual(oflds[pks[i]].name(), kfnames[i])
开发者ID:lucacasagrande,项目名称:QGIS,代码行数:29,代码来源:test_provider_postgres.py

示例3: testKey

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
 def testKey(lyr, key, kfnames):
     self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.import_test')
     uri = '%s table="qgis_test"."import_test" (g) key=\'%s\'' % (self.dbconn, key)
     err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs())
     self.assertEqual(err[0], QgsVectorLayerImport.NoError,
                      'unexpected import error {0}'.format(err))
     olyr = QgsVectorLayer(uri, "y", "postgres")
     self.assertTrue(olyr.isValid())
     flds = lyr.fields()
     oflds = olyr.fields()
     self.assertEquals(oflds.size(), flds.size())
     for i in range(0, oflds.size()):
         self.assertEqual(oflds[i].name(), flds[i].name())
     pks = olyr.pkAttributeList()
     self.assertEquals(len(pks), len(kfnames))
     for i in range(0, len(kfnames)):
         self.assertEqual(oflds[pks[i]].name(), kfnames[i])
开发者ID:mterente,项目名称:QGIS,代码行数:19,代码来源:test_provider_postgres.py

示例4: testNumericPrecision

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
 def testNumericPrecision(self):
     uri = "point?field=f1:int"
     uri += "&field=f2:double(6,4)"
     uri += "&field=f3:string(20)"
     lyr = QgsVectorLayer(uri, "x", "memory")
     self.assertTrue(lyr.isValid())
     f = QgsFeature(lyr.fields())
     f["f1"] = 1
     f["f2"] = 123.456
     f["f3"] = "12345678.90123456789"
     lyr.dataProvider().addFeatures([f])
     uri = '%s table="qgis_test"."b18155" (g) key=\'f1\'' % (self.dbconn)
     self.execSQLCommand("DROP TABLE IF EXISTS qgis_test.b18155")
     err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs())
     self.assertEqual(err[0], QgsVectorLayerImport.NoError, "unexpected import error {0}".format(err))
     lyr = QgsVectorLayer(uri, "y", "postgres")
     self.assertTrue(lyr.isValid())
     f = next(lyr.getFeatures())
     self.assertEqual(f["f1"], 1)
     self.assertEqual(f["f2"], 123.456)
     self.assertEqual(f["f3"], "12345678.90123456789")
开发者ID:Gustry,项目名称:QGIS,代码行数:23,代码来源:test_provider_postgres.py

示例5: processAlgorithm

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
    def processAlgorithm(self, progress):
        database = self.getParameterValue(self.DATABASE)
        uri = QgsDataSourceUri(database)
        if uri.database() is '':
            if '|layerid' in database:
                database = database[:database.find('|layerid')]
            uri = QgsDataSourceUri('dbname=\'%s\'' % (database))
        db = spatialite.GeoDB(uri)

        overwrite = self.getParameterValue(self.OVERWRITE)
        createIndex = self.getParameterValue(self.CREATEINDEX)
        convertLowerCase = self.getParameterValue(self.LOWERCASE_NAMES)
        dropStringLength = self.getParameterValue(self.DROP_STRING_LENGTH)
        forceSinglePart = self.getParameterValue(self.FORCE_SINGLEPART)
        primaryKeyField = self.getParameterValue(self.PRIMARY_KEY) or 'id'
        encoding = self.getParameterValue(self.ENCODING)

        layerUri = self.getParameterValue(self.INPUT)
        layer = dataobjects.getObjectFromUri(layerUri)

        table = self.getParameterValue(self.TABLENAME)
        if table:
            table.strip()
        if not table or table == '':
            table = layer.name()
        table = table.replace(' ', '').lower()
        providerName = 'spatialite'

        geomColumn = self.getParameterValue(self.GEOMETRY_COLUMN)
        if not geomColumn:
            geomColumn = 'the_geom'

        options = {}
        if overwrite:
            options['overwrite'] = True
        if convertLowerCase:
            options['lowercaseFieldNames'] = True
            geomColumn = geomColumn.lower()
        if dropStringLength:
            options['dropStringConstraints'] = True
        if forceSinglePart:
            options['forceSinglePartGeometryType'] = True

        # Clear geometry column for non-geometry tables
        if not layer.hasGeometryType():
            geomColumn = None

        uri = db.uri
        uri.setDataSource('', table, geomColumn, '', primaryKeyField)

        if encoding:
            layer.setProviderEncoding(encoding)

        (ret, errMsg) = QgsVectorLayerImport.importLayer(
            layer,
            uri.uri(),
            providerName,
            self.crs,
            False,
            False,
            options,
        )
        if ret != 0:
            raise GeoAlgorithmExecutionException(
                self.tr('Error importing to Spatialite\n%s' % errMsg))

        if geomColumn and createIndex:
            db.create_spatial_index(table, geomColumn)
开发者ID:drnextgis,项目名称:QGIS,代码行数:70,代码来源:ImportIntoSpatialite.py

示例6: accept

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
    def accept(self):
        if self.mode == self.ASK_FOR_INPUT_MODE:
            # create the input layer (if not already done) and
            # update available options
            self.reloadInputLayer()

        # sanity checks
        if self.inLayer is None:
            QMessageBox.information(self, self.tr("Import to database"), self.tr("Input layer missing or not valid"))
            return

        if self.cboTable.currentText() == "":
            QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = self.editSourceSrid.text()
            except ValueError:
                QMessageBox.information(self, self.tr("Import to database"),
                                        self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = self.editTargetSrid.text()
            except ValueError:
                QMessageBox.information(self, self.tr("Import to database"),
                                        self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs and encoding, so I can restore it
        prevInCrs = self.inLayer.crs()
        prevInEncoding = self.inLayer.dataProvider().encoding()

        try:
            schema = self.outUri.schema() if not self.cboSchema.isEnabled() else self.cboSchema.currentText()
            table = self.cboTable.currentText()

            # get pk and geom field names from the source layer or use the
            # ones defined by the user
            srcUri = QgsDataSourceUri(self.inLayer.source())

            pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text()
            if not pk:
                pk = self.default_pk

            if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled():
                geom = srcUri.geometryColumn() if not self.chkGeomColumn.isChecked() else self.editGeomColumn.text()
                if not geom:
                    geom = self.default_geom
            else:
                geom = None

            options = {}
            if self.chkLowercaseFieldNames.isEnabled() and self.chkLowercaseFieldNames.isChecked():
                pk = pk.lower()
                if geom:
                    geom = geom.lower()
                options['lowercaseFieldNames'] = True

            # get output params, update output URI
            self.outUri.setDataSource(schema, table, geom, "", pk)
            uri = self.outUri.uri(False)

            providerName = self.db.dbplugin().providerName()
            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked():
                options['forceSinglePartGeometryType'] = True

            outCrs = QgsCoordinateReferenceSystem()
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
                targetSrid = int(self.editTargetSrid.text())
                outCrs = QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs and encoding
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                self.inLayer.setProviderEncoding(enc)

            onlySelected = self.chkSelectedFeatures.isChecked()

            # do the import!
            ret, errMsg = QgsVectorLayerImport.importLayer(self.inLayer, uri, providerName, outCrs, onlySelected, False, options)
        except Exception as e:
            ret = -1
            errMsg = str(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
#.........这里部分代码省略.........
开发者ID:drnextgis,项目名称:QGIS,代码行数:103,代码来源:dlg_import_vector.py

示例7: QgsDataSourceURI

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
 uri = QgsDataSourceURI()
 uri.setConnection(host, str(port), database, username, password)
 newCrs = QgsCoordinateReferenceSystem()
 newCrs.createFromUserInput(u"EPSG:2154")
 
 #Gid = cle primaire par defaut
 uri.setDataSource(schema, table, geomColumn, '', "gid")
 
 progress.setInfo(u"Importation de la table vers PostgreSQL (cela peut prendre un moment)")
 
 #Import
 (ret, errMsg) = QgsVectorLayerImport.importLayer(
     layer,
     uri.uri(),
     providerName,
     newCrs,
     False,
     False,
     options,
 )
 if ret != 0:
     raise GeoAlgorithmExecutionException(
         self.tr('Erreur importation dans PostGIS\n%s' % errMsg))
         
 if primaryKeyField:
     sql2 ="""alter table "{schema}".{table} drop constraint {table}_pkey;""".format(schema=schema,table=table)
     sql2 +="""alter table "{schema}".{table} add primary key ({primaryKeyField});""".format(schema=schema,table=table,primaryKeyField=primaryKeyField)
     sql2 +="""COMMIT;"""
     
     try:
         db._exec_sql_and_commit(str(sql2))
开发者ID:MacPoulet,项目名称:dirnoProvider1,代码行数:33,代码来源:ImportIntoDirnoPostgis.py

示例8: accept

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
    def accept(self):
        # sanity checks
        if self.editOutputFile.text() == "":
            QMessageBox.information(self, self.tr("Export to file"), self.tr("Output file name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = int(self.editSourceSrid.text())
            except ValueError:
                QMessageBox.information(self, self.tr("Export to file"),
                                        self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = int(self.editTargetSrid.text())
            except ValueError:
                QMessageBox.information(self, self.tr("Export to file"),
                                        self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs, so I can restore it later
        prevInCrs = self.inLayer.crs()
        try:
            uri = self.editOutputFile.text()
            providerName = "ogr"

            options = {}

            # set the OGR driver will be used
            driverName = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex())
            options['driverName'] = driverName

            # set the output file encoding
            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                options['fileEncoding'] = enc

            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            outCrs = None
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
                targetSrid = int(self.editTargetSrid.text())
                outCrs = QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            # do the export!
            ret, errMsg = QgsVectorLayerImport.importLayer(self.inLayer, uri, providerName, outCrs, False,
                                                           False, options)
        except Exception as e:
            ret = -1
            errMsg = unicode(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
            # restore cursor
            QApplication.restoreOverrideCursor()

        if ret != 0:
            QMessageBox.warning(self, self.tr("Export to file"), self.tr("Error %d\n%s") % (ret, errMsg))
            return

        # create spatial index
        # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked():
        #       self.db.connector.createSpatialIndex( (schema, table), geom )

        QMessageBox.information(self, self.tr("Export to file"), self.tr("Export finished."))
        return QDialog.accept(self)
开发者ID:volaya,项目名称:QGIS,代码行数:80,代码来源:dlg_export_vector.py

示例9: processAlgorithm

# 需要导入模块: from qgis.core import QgsVectorLayerImport [as 别名]
# 或者: from qgis.core.QgsVectorLayerImport import importLayer [as 别名]
    def processAlgorithm(self, progress):
        connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)]
        schema = self.getParameterValue(self.SCHEMA)
        overwrite = self.getParameterValue(self.OVERWRITE)
        createIndex = self.getParameterValue(self.CREATEINDEX)
        convertLowerCase = self.getParameterValue(self.LOWERCASE_NAMES)
        dropStringLength = self.getParameterValue(self.DROP_STRING_LENGTH)
        primaryKeyField = self.getParameterValue(self.PRIMARY_KEY)
        settings = QSettings()
        mySettings = '/PostgreSQL/connections/' + connection
        try:
            database = settings.value(mySettings + '/database')
            username = settings.value(mySettings + '/username')
            host = settings.value(mySettings + '/host')
            port = settings.value(mySettings + '/port', type=int)
            password = settings.value(mySettings + '/password')
        except Exception as e:
            raise GeoAlgorithmExecutionException(
                self.tr('Wrong database connection name: %s' % connection))

        layerUri = self.getParameterValue(self.INPUT)
        layer = dataobjects.getObjectFromUri(layerUri)

        table = self.getParameterValue(self.TABLENAME).strip()
        if table == '':
            table = layer.name()
        table = table.replace(' ', '').lower()
        providerName = 'postgres'

        try:
            db = postgis_utils.GeoDB(host=host, port=port, dbname=database,
                                     user=username, passwd=password)
        except postgis_utils.DbError as e:
            raise GeoAlgorithmExecutionException(
                self.tr("Couldn't connect to database:\n%s" % e.message))

        geomColumn = self.getParameterValue(self.GEOMETRY_COLUMN)
        if not geomColumn:
            geomColumn = 'the_geom'

        options = {}
        if overwrite:
            options['overwrite'] = True
        if convertLowerCase:
            options['lowercaseFieldNames'] = True
            geomColumn = geomColumn.lower()
        if dropStringLength:
            options['dropStringConstraints'] = True

        #clear geometry column for non-geometry tables
        if not layer.hasGeometryType():
            geomColumn = None

        uri = QgsDataSourceURI()
        uri.setConnection(host, unicode(port), database, username, password)
        if primaryKeyField:
            uri.setDataSource(schema, table, geomColumn, '', primaryKeyField)
        else:
            uri.setDataSource(schema, table, geomColumn, '')

        (ret, errMsg) = QgsVectorLayerImport.importLayer(
            layer,
            uri.uri(),
            providerName,
            self.crs,
            False,
            False,
            options,
        )
        if ret != 0:
            raise GeoAlgorithmExecutionException(
                self.tr('Error importing to PostGIS\n%s' % errMsg))

        if geomColumn and createIndex:
            db.create_spatial_index(table, schema, geomColumn)

        db.vacuum_analyze(table, schema)
开发者ID:Geoneer,项目名称:QGIS,代码行数:79,代码来源:ImportIntoPostGIS.py


注:本文中的qgis.core.QgsVectorLayerImport.importLayer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。