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


Python core.QgsDataSourceUri类代码示例

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


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

示例1: testTableDataModel

    def testTableDataModel(self):
        connection_name = 'testTableDataModel'
        plugin = createDbPlugin('spatialite')
        uri = QgsDataSourceUri()
        uri.setDatabase(self.test_spatialite)
        self.assertTrue(plugin.addConnection(connection_name, uri))

        connection = createDbPlugin('spatialite', connection_name)
        connection.connect()

        db = connection.database()
        self.assertIsNotNone(db)

        tables = db.tables()
        self.assertEqual(len(tables), 1)
        table = tables[0]
        self.assertEqual(table.name, 'testlayer')
        model = table.tableDataModel(None)

        self.assertEqual(model.rowCount(), 1)
        self.assertEqual(model.getData(0, 0), 1)  # fid

        wkb = model.getData(0, 1)
        geometry = ogr.CreateGeometryFromWkb(wkb)
        self.assertEqual(geometry.ExportToWkt(), 'LINESTRING (1 2,3 4)')

        self.assertEqual(model.getData(0, 2), 'foo')

        connection.remove()
开发者ID:manisandro,项目名称:QGIS,代码行数:29,代码来源:test_db_manager_spatialite.py

示例2: onUpdateSqlLayer

 def onUpdateSqlLayer(self):
     l = self.iface.activeLayer()
     if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']:
         table = QgsDataSourceUri(l.source()).table()
         if table.startswith('(') and table.endswith(')'):
             self.run()
             self.dlg.runSqlLayerWindow(l)
开发者ID:cayetanobv,项目名称:QGIS,代码行数:7,代码来源:db_manager_plugin.py

示例3: onUpdateSqlLayer

 def onUpdateSqlLayer(self):
     l = self.iface.activeLayer()
     if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']:
         uri = QgsDataSourceUri(l.source())
         if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S):
             self.run()
             self.dlg.runSqlLayerWindow(l)
开发者ID:Gustry,项目名称:QGIS,代码行数:7,代码来源:db_manager_plugin.py

示例4: _clearSslTempCertsIfAny

    def _clearSslTempCertsIfAny(self, connectionInfo):
        # remove certs (if any) of the connectionInfo
        expandedUri = QgsDataSourceUri(connectionInfo)

        def removeCert(certFile):
            certFile = certFile.replace("'", "")
            file = QFile(certFile)
            # set permission to allow removing on Win.
            # On linux and Mac if file is set with QFile::>ReadUser
            # does not create problem removing certs
            if not file.setPermissions(QFile.WriteOwner):
                raise Exception('Cannot change permissions on {}: error code: {}'.format(file.fileName(), file.error()))
            if not file.remove():
                raise Exception('Cannot remove {}: error code: {}'.format(file.fileName(), file.error()))

        sslCertFile = expandedUri.param("sslcert")
        if sslCertFile:
            removeCert(sslCertFile)

        sslKeyFile = expandedUri.param("sslkey")
        if sslKeyFile:
            removeCert(sslKeyFile)

        sslCAFile = expandedUri.param("sslrootcert")
        if sslCAFile:
            removeCert(sslCAFile)
开发者ID:FERRATON,项目名称:QGIS,代码行数:26,代码来源:connector.py

示例5: onUpdateSqlLayer

 def onUpdateSqlLayer(self):
     l = self.iface.legendInterface().currentLayer()
     if l.dataProvider().name() in ["postgres", "spatialite", "oracle"]:
         uri = QgsDataSourceUri(l.source())
         if re.search("^\(SELECT .+ FROM .+\)$", uri.table(), re.S):
             self.run()
             self.dlg.runSqlLayerWindow(l)
开发者ID:CS-SI,项目名称:QGIS,代码行数:7,代码来源:db_manager_plugin.py

示例6: connect

    def connect(self, selected, parent=None):
        settings = QSettings()
        settings.beginGroup(u"/%s/connections/%s" % (self.getSettingsKey(), selected))

        if not settings.contains("database"):  # non-existent entry?
            raise DbError('there is no defined database connection "%s".' % selected)

        get_value_str = lambda x: str(settings.value(x) if Utils.isSIPv2() else settings.value(x).toString())
        service, host, port, database, username, password = list(map(get_value_str, ["service", "host", "port", "database", "username", "password"]))

        # qgis1.5 use 'savePassword' instead of 'save' setting
        isSave = settings.value("save") if Utils.isSIPv2() else settings.value("save").toBool()
        isSavePassword = settings.value("savePassword") if Utils.isSIPv2() else settings.value("savePassword").toBool()
        if not (isSave or isSavePassword):
            (password, ok) = QInputDialog.getText(parent, "Enter password", 'Enter password for connection "%s":' % selected, QLineEdit.Password)
            if not ok: return

        settings.endGroup()

        uri = QgsDataSourceUri()
        if service:
            uri.setConnection(service, database, username, password)
        else:
            uri.setConnection(host, port, database, username, password)

        return Connection(uri)
开发者ID:pgRouting,项目名称:pgRoutingLayer,代码行数:26,代码来源:postgis.py

示例7: testWfsSettings

    def testWfsSettings(self):
        uri = QgsDataSourceUri()
        QgsOwsConnection.addWfsConnectionSettings(uri, 'qgis/connections-wfs/test/')

        self.assertEqual(uri.param('version'), '1.1.0')
        self.assertEqual(uri.param('maxNumFeatures'), '47')
        self.assertEqual(uri.param('IgnoreAxisOrientation'), '1')
        self.assertEqual(uri.param('InvertAxisOrientation'), '1')
开发者ID:CS-SI,项目名称:QGIS,代码行数:8,代码来源:test_qgsowsconnection.py

示例8: dropMimeData

    def dropMimeData(self, data, action, row, column, parent):
        global isImportVectorAvail

        if action == Qt.IgnoreAction:
            return True

        # vectors/tables to be imported must be dropped on connected db, schema or table
        canImportLayer = isImportVectorAvail and parent.isValid() and \
            (isinstance(parent.internalPointer(), (SchemaItem, TableItem)) or
             (isinstance(parent.internalPointer(), ConnectionItem) and parent.internalPointer().populated))

        added = 0

        if data.hasUrls():
            for u in data.urls():
                filename = u.toLocalFile()
                if filename == "":
                    continue

                if self.hasSpatialiteSupport:
                    from .db_plugins.spatialite.connector import SpatiaLiteDBConnector

                    if SpatiaLiteDBConnector.isValidDatabase(filename):
                        # retrieve the SL plugin tree item using its path
                        index = self._rPath2Index(["spatialite"])
                        if not index.isValid():
                            continue
                        item = index.internalPointer()

                        conn_name = QFileInfo(filename).fileName()
                        uri = QgsDataSourceUri()
                        uri.setDatabase(filename)
                        item.getItemData().addConnection(conn_name, uri)
                        item.changed.emit()
                        added += 1
                        continue

                if canImportLayer:
                    if QgsRasterLayer.isValidRasterFileName(filename):
                        layerType = 'raster'
                        providerKey = 'gdal'
                    else:
                        layerType = 'vector'
                        providerKey = 'ogr'

                    layerName = QFileInfo(filename).completeBaseName()
                    if self.importLayer(layerType, providerKey, layerName, filename, parent):
                        added += 1

        if data.hasFormat(self.QGIS_URI_MIME):
            for uri in QgsMimeDataUtils.decodeUriList(data):
                if canImportLayer:
                    if self.importLayer(uri.layerType, uri.providerKey, uri.name, uri.uri, parent):
                        added += 1

        return added > 0
开发者ID:NyakudyaA,项目名称:QGIS,代码行数:56,代码来源:db_model.py

示例9: postgis_path_to_uri

    def postgis_path_to_uri(path):
        """Convert layer path from QgsBrowserModel to full QgsDataSourceUri.

        :param path: The layer path from QgsBrowserModel
        :type path: string

        :returns: layer uri.
        :rtype: QgsDataSourceUri
        """

        connection_name = path.split('/')[1]
        schema = path.split('/')[2]
        table_name = path.split('/')[3]

        settings = QSettings()
        key = "/PostgreSQL/connections/" + connection_name
        service = settings.value(key + "/service")
        host = settings.value(key + "/host")
        port = settings.value(key + "/port")
        if not port:
            port = "5432"
        db = settings.value(key + "/database")
        use_estimated_metadata = settings.value(
            key + "/estimatedMetadata", False, type=bool)
        sslmode = settings.value(
            key + "/sslmode", QgsDataSourceUri.SSLprefer, type=int)
        username = ""
        password = ""
        if settings.value(key + "/saveUsername") == "true":
            username = settings.value(key + "/username")

        if settings.value(key + "/savePassword") == "true":
            password = settings.value(key + "/password")

        # Old save setting
        if settings.contains(key + "/save"):
            username = settings.value(key + "/username")
            if settings.value(key + "/save") == "true":
                password = settings.value(key + "/password")

        uri = QgsDataSourceUri()
        if service:
            uri.setConnection(service, db, username, password, sslmode)
        else:
            uri.setConnection(host, port, db, username, password, sslmode)

        uri.setUseEstimatedMetadata(use_estimated_metadata)

        # Obtain the geometry column name
        connector = PostGisDBConnector(uri)
        tables = connector.getVectorTables(schema)
        tables = [table for table in tables if table[1] == table_name]
        if not tables:
            return None
        table = tables[0]
        geom_col = table[8]

        uri.setDataSource(schema, table_name, geom_col)
        return uri
开发者ID:inasafe,项目名称:inasafe,代码行数:59,代码来源:wizard_step_browser.py

示例10: processAlgorithm

 def processAlgorithm(self, feedback):
     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))
     self.db = spatialite.GeoDB(uri)
     sql = self.getParameterValue(self.SQL).replace("\n", " ")
     try:
         self.db._exec_sql_and_commit(str(sql))
     except spatialite.DbError as e:
         raise GeoAlgorithmExecutionException(self.tr("Error executing SQL:\n%s") % str(e))
开发者ID:Gustry,项目名称:QGIS,代码行数:13,代码来源:SpatialiteExecuteSQL.py

示例11: testExecuteRegExp

    def testExecuteRegExp(self):
        """This test checks for REGEXP syntax support, which is enabled in Qgis.utils' spatialite_connection()"""

        connection_name = 'testListLayer'
        plugin = createDbPlugin('spatialite')
        uri = QgsDataSourceUri()
        uri.setDatabase(self.test_spatialite)
        self.assertTrue(plugin.addConnection(connection_name, uri))

        connection = createDbPlugin('spatialite', connection_name)
        connection.connect()
        db = connection.database()
        db.connector._execute(None, 'SELECT \'ABC\' REGEXP \'[CBA]\'')
开发者ID:boundlessgeo,项目名称:QGIS,代码行数:13,代码来源:test_db_manager_spatialite.py

示例12: connect

    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QgsSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("sqlitepath"):  # non-existent entry?
            raise InvalidDataException(self.tr(u'There is no defined database connection "{0}".').format(conn_name))

        database = settings.value("sqlitepath")

        uri = QgsDataSourceUri()
        uri.setDatabase(database)
        return self.connectToUri(uri)
开发者ID:GeoCat,项目名称:QGIS,代码行数:13,代码来源:plugin.py

示例13: importLayer

    def importLayer(self, layerType, providerKey, layerName, uriString, parent):
        global isImportVectorAvail

        if not isImportVectorAvail:
            return False

        if layerType == 'raster':
            return False  # not implemented yet
            inLayer = QgsRasterLayer(uriString, layerName, providerKey)
        else:
            inLayer = QgsVectorLayer(uriString, layerName, providerKey)

        if not inLayer.isValid():
            # invalid layer
            QMessageBox.warning(None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name())
            return False

        # retrieve information about the new table's db and schema
        outItem = parent.internalPointer()
        outObj = outItem.getItemData()
        outDb = outObj.database()
        outSchema = None
        if isinstance(outItem, SchemaItem):
            outSchema = outObj
        elif isinstance(outItem, TableItem):
            outSchema = outObj.schema()

        # toIndex will point to the parent item of the new table
        toIndex = parent
        if isinstance(toIndex.internalPointer(), TableItem):
            toIndex = toIndex.parent()

        if inLayer.type() == inLayer.VectorLayer:
            # create the output uri
            schema = outSchema.name if outDb.schemas() is not None and outSchema is not None else ""
            pkCol = geomCol = ""

            # default pk and geom field name value
            if providerKey in ['postgres', 'spatialite']:
                inUri = QgsDataSourceUri(inLayer.source())
                pkCol = inUri.keyColumn()
                geomCol = inUri.geometryColumn()

            outUri = outDb.uri()
            outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

            self.importVector.emit(inLayer, outDb, outUri, toIndex)
            return True

        return False
开发者ID:NyakudyaA,项目名称:QGIS,代码行数:50,代码来源:db_model.py

示例14: addConnectionActionSlot

    def addConnectionActionSlot(self, item, action, parent, index):
        QApplication.restoreOverrideCursor()
        try:
            filename, selected_filter = QFileDialog.getOpenFileName(parent, "Choose SQLite/SpatiaLite file")
            if not filename:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        conn_name = QFileInfo(filename).fileName()
        uri = QgsDataSourceUri()
        uri.setDatabase(filename)
        self.addConnection(conn_name, uri)
        index.internalPointer().itemChanged()
开发者ID:GeoCat,项目名称:QGIS,代码行数:14,代码来源:plugin.py

示例15: copy

    def copy(self, target_path, copied_files, keep_existent=False):
        """
        Copy a layer to a new path and adjust its datasource.

        :param layer: The layer to copy
        :param target_path: A path to a folder into which the data will be copied
        :param keep_existent: if True and target file already exists, keep it as it is
        """
        if not self.is_file:
            # Copy will also be called on non-file layers like WMS. In this case, just do nothing.
            return

        layer_name_suffix = ''
        # Shapefiles and GeoPackages have the path in the source
        uri_parts = self.layer.source().split('|', 1)
        file_path = uri_parts[0]
        if len(uri_parts) > 1:
            layer_name_suffix = uri_parts[1]
        # Spatialite have the path in the table part of the uri
        uri = QgsDataSourceUri(self.layer.dataProvider().dataSourceUri())

        if os.path.isfile(file_path):
            source_path, file_name = os.path.split(file_path)
            basename, extensions = get_file_extension_group(file_name)
            for ext in extensions:
                dest_file = os.path.join(target_path, basename + ext)
                if os.path.exists(os.path.join(source_path, basename + ext)) and \
                        (keep_existent is False or not os.path.isfile(dest_file)):
                    shutil.copy(os.path.join(source_path, basename + ext), dest_file)

            new_source = os.path.join(target_path, file_name)
            if layer_name_suffix:
                new_source = new_source + '|' + layer_name_suffix
            self._change_data_source(new_source)
        # Spatialite files have a uri
        else:
            file_path = uri.database()
            if os.path.isfile(file_path):
                source_path, file_name = os.path.split(file_path)
                basename, extensions = get_file_extension_group(file_name)
                for ext in extensions:
                    dest_file = os.path.join(target_path, basename + ext)
                    if os.path.exists(os.path.join(source_path, basename + ext)) and \
                            (keep_existent is False or not os.path.isfile(dest_file)):
                        shutil.copy(os.path.join(source_path, basename + ext),
                                    dest_file)
                uri.setDatabase(os.path.join(target_path, file_name))
                self._change_data_source(uri.uri())
        return copied_files
开发者ID:opengisch,项目名称:QFieldSync,代码行数:49,代码来源:layer.py


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