本文整理汇总了Python中qgis.core.QgsDataSourceURI类的典型用法代码示例。如果您正苦于以下问题:Python QgsDataSourceURI类的具体用法?Python QgsDataSourceURI怎么用?Python QgsDataSourceURI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QgsDataSourceURI类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: pg_layerNamesIDMapping
def pg_layerNamesIDMapping():
'''
Returns a dictionary containing the original table names and corresponding layer IDs in the
QGIS legend for only those layers from a postgres database.
'''
mapping = ReverseDict()
layers = QgsMapLayerRegistry.instance().mapLayers()
for name,layer in layers.iteritems():
if hasattr(layer, 'dataProvider'):
if layer.dataProvider().name() == 'postgres':
layerConnStr = layer.dataProvider().dataSourceUri()
dataSourceURI = QgsDataSourceURI(layerConnStr)
mapping[dataSourceURI.table()] = layer.id()
return mapping
开发者ID:7o9,项目名称:stdm-plugin,代码行数:16,代码来源:utils.py
示例2: connect
def connect(self, parent=None):
conn_name = self.connectionName()
settings = QSettings()
settings.beginGroup( u"/%s/%s" % (self.connectionSettingsKey(), conn_name) )
if not settings.contains( "database" ): # non-existent entry?
raise InvalidDataException( u'there is no defined database connection "%s".' % conn_name )
from qgis.core import QgsDataSourceURI
uri = QgsDataSourceURI()
get_value_str = lambda x: settings.value(x).toString()
host, port, database, username, password = map(get_value_str, ["host", "port", "database", "username", "password"])
# qgis1.5 use 'savePassword' instead of 'save' setting
savedPassword = settings.value("save", False).toBool() or settings.value("savePassword", False).toBool()
useEstimatedMetadata = settings.value("estimatedMetadata", False).toBool()
sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer).toInt()[0]
settings.endGroup()
uri.setConnection(host, port, database, username, password, sslmode)
uri.setUseEstimatedMetadata(useEstimatedMetadata)
err = QString()
try:
return DBPlugin.connect(self, uri)
except ConnectionError, e:
err = QString( str(e) )
开发者ID:netconstructor,项目名称:db_manager,代码行数:30,代码来源:plugin.py
示例3: 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:Zakui,项目名称:QGIS,代码行数:7,代码来源:db_manager_plugin.py
示例4: getAll
def getAll(self, expression=None):
uri = QgsDataSourceURI(expression)
if uri.table() != self.layer:
raise Exception('Invalid expression %s. Expected table %s but got %s'%(expression, self.layer, uri.table))
qgsLayer = getLayerByUri(self.layer, uri.uri())
if not qgsLayer:
raise Exception('Layer with uri %s not found'%QgsDataSourceURI.removePassword(uri.uri()))
开发者ID:archeocs,项目名称:qazp-framework,代码行数:7,代码来源:utils.py
示例5: ogrConnectionString
def ogrConnectionString(self, uri):
ogrstr = None
layer = dataobjects.getObjectFromUri(uri, False)
if layer is None:
return uri
provider = layer.dataProvider().name()
if provider == 'spatialite':
# dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
regex = re.compile("dbname='(.+)'")
r = regex.search(unicode(layer.source()))
ogrstr = r.groups()[0]
elif provider == 'postgres':
# dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
# user='ktryjh_iuuqef' password='xyqwer' sslmode=disable
# key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
# table="t4" (geom) sql=
dsUri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
connInfo = dsUri.connectionInfo()
(success, user, passwd ) = QgsCredentials.instance().get(connInfo, None, None)
if success:
QgsCredentials.instance().put(connInfo, user, passwd)
ogrstr = ("PG:dbname='%s' host='%s' port='%s' user='%s' password='%s'"
% (dsUri.database(), dsUri.host(), dsUri.port(), user, passwd))
else:
ogrstr = unicode(layer.source()).split("|")[0]
return '"' + ogrstr + '"'
开发者ID:Ariki,项目名称:QGIS,代码行数:27,代码来源:OgrAlgorithm.py
示例6: get_db_tables
def get_db_tables(self):
"""Retrieve all tables from the selected database."""
self.dlg.cmb_geo.clear()
db_name = self.dlg.cmb_db.currentText()
con_name = self.dlg.cmb_con.currentText()
con_str = "{db}/connections/{con}/".format(db=db_name, con=con_name)
qs = QSettings()
db_host = qs.value(con_str + "host")
db_port = qs.value(con_str + "port")
db_name = qs.value(con_str + "database")
con_usr = qs.value(con_str + "username")
con_pwd = qs.value(con_str + "password")
uri = QgsDataSourceURI()
uri.setConnection(db_host, db_port, db_name, con_usr, con_pwd)
post_c = pg_con.PostGisDBConnector(uri)
tbl_list = []
for table in post_c.getTables():
if table[3] or table[1] == 'spatial_ref_sys':
pass
else:
tbl_list.append(table[1])
if len(tbl_list) == 0:
QMessageBox.warning(None,
'Layer and Tables',
"""There are no tables to geo-code in this database.""")
else:
self.dlg.cmb_geo.addItems(tbl_list)
开发者ID:TomGeoDK,项目名称:geonames-geocoder,代码行数:27,代码来源:geonames_geocoder.py
示例7: createBlockLayer
def createBlockLayer(self):
uri = QgsDataSourceURI()
uri.setConnection(self.db_hostName, str(self.db_Port), self.db_databaseName, self.db_UserName, self.db_password)
uri.setDataSource("cadastre", "spatial_unit_group", "geom", "hierarchy_level=5")
uri.uri()
print uri.uri()
rlayer = self.iface.addVectorLayer(uri.uri(), "Blocks", "postgres")
rlayer.loadNamedStyle(self.plugin_dir + '/lga.qml')
开发者ID:SLTR-Portal,项目名称:sltr-plugin,代码行数:8,代码来源:sltr.py
示例8: getLayers
def getLayers(self, dbName):
lyrList = []
for lyr in self.iface.legendInterface().layers():
if isinstance(lyr, QgsVectorLayer):
candidateUri = QgsDataSourceURI(lyr.dataProvider().dataSourceUri())
if candidateUri.database() == dbName and lyr.providerType() in ['postgres', 'spatialite']:
lyrList.append(lyr)
return lyrList
开发者ID:lcoandrade,项目名称:DsgTools,代码行数:8,代码来源:styleManagerTool.py
示例9: getLayerByUri
def getLayerByUri(layerName, uri):
reg = QgsMapLayerRegistry.instance()
allLayers = reg.mapLayersByName(layerName)
for a in allLayers:
dsUri = QgsDataSourceURI(a.dataProvider().dataSourceUri())
if dsUri.uri() == uri:
return a
return None
开发者ID:archeocs,项目名称:qazp-framework,代码行数:8,代码来源:utils.py
示例10: getDatabaseList
def getDatabaseList(self):
dbList = []
for lyr in self.iface.legendInterface().layers():
if isinstance(lyr, QgsVectorLayer):
candidateUri = QgsDataSourceURI(lyr.dataProvider().dataSourceUri())
dbName = candidateUri.database()
if dbName not in dbList and lyr.providerType() in ['postgres', 'spatialite']:
dbList.append(dbName)
return dbList
开发者ID:lcoandrade,项目名称:DsgTools,代码行数:9,代码来源:styleManagerTool.py
示例11: 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.itemChanged.emit(item)
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:LKajan,项目名称:QGIS,代码行数:56,代码来源:db_model.py
示例12: toQgsDataSourceUri
def toQgsDataSourceUri(self):
"""
Returns a QgsDataSourceURI object with database connection properties
defined.
"""
dt_source = QgsDataSourceURI()
dt_source.setConnection(self.Host, unicode(self.Port), self.Database,
self.User.UserName, unicode(self.User.Password))
return dt_source
开发者ID:gltn,项目名称:stdm,代码行数:10,代码来源:connection.py
示例13: fromLayer
def fromLayer(cls, layer):
uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
connectioninfo = {
"host": uri.host(),
"database": uri.database(),
"user": uri.username(),
"password": uri.password(),
"connectionname": layer.id()
}
database = Database.connect(**connectioninfo)
return database
开发者ID:henriquespedro,项目名称:Roam,代码行数:11,代码来源:database.py
示例14: 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:akbargumbira,项目名称:inasafe,代码行数:59,代码来源:wizard_step_browser.py
示例15: connect
def connect(self, parent=None):
conn_name = self.connectionName()
settings = QSettings()
settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))
if not settings.contains("sqlitepath"): # non-existent entry?
raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name)
database = settings.value("sqlitepath")
uri = QgsDataSourceURI()
uri.setDatabase(database)
return self.connectToUri(uri)
开发者ID:Jesonchang12,项目名称:QGIS,代码行数:13,代码来源:plugin.py
示例16: makeValueRelationDict
def makeValueRelationDict(self, valueDict):
ret = dict()
codes = valueDict['FilterExpression'].replace('code in (', '').replace(')','').split(',')
keyColumn = valueDict['Key']
valueColumn = valueDict['Value']
table = valueDict['Layer'][:-17]#removing the date-time characters
uri = QgsDataSourceURI(self.currLayer.dataProvider().dataSourceUri())
if uri.host() == '':
db = QSqlDatabase('QSQLITE')
db.setDatabaseName(uri.database())
else:
db = QSqlDatabase('QPSQL')
db.setHostName(uri.host())
db.setPort(int(uri.port()))
db.setDatabaseName(uri.database())
db.setUserName(uri.username())
db.setPassword(uri.password())
if not db.open():
db.close()
return ret
in_clause = ','.join(map(str, codes))
query = QSqlQuery('select code, code_name from dominios.%s where code in (%s)' % (table, in_clause), db)
while query.next():
code = str(query.value(0))
code_name = query.value(1)
ret[code_name] = code
db.close()
return ret
开发者ID:alexdsz,项目名称:DsgTools,代码行数:34,代码来源:code_list.py
示例17: fromLayer
def fromLayer(cls, layer):
source = layer.source()
uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
if ".sqlite" in source:
try:
index = source.index("|")
source = source[:index]
except ValueError:
pass
if uri.database():
source = uri.database()
connectioninfo = {"type": "QSQLITE",
"database": source}
else:
uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())
connectioninfo = {
"host": uri.host(),
"database": uri.database(),
"user": uri.username(),
"password": uri.password()
}
connectioninfo["connectionname"] = layer.id()
database = Database.connect(**connectioninfo)
return database
开发者ID:loongfee,项目名称:Roam,代码行数:25,代码来源:database.py
示例18: checkLoaded
def checkLoaded(self, name, loadedLayers):
"""
Checks if the layers is already loaded in the QGIS' TOC
:param name:
:param loadedLayers:
:return:
"""
loaded = None
for ll in loadedLayers:
if ll.name() == name:
candidateUri = QgsDataSourceURI(ll.dataProvider().dataSourceUri())
if self.host == candidateUri.host() and self.database == candidateUri.database() and self.port == int(candidateUri.port()):
return ll
return loaded
开发者ID:lcoandrade,项目名称:DsgTools,代码行数:14,代码来源:postgisLayerLoader.py
示例19: addConnectionActionSlot
def addConnectionActionSlot(self, item, action, parent, index):
QApplication.restoreOverrideCursor()
try:
filename = QFileDialog.getOpenFileName(parent, "Choose Sqlite/Spatialite/Geopackage 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().emit(SIGNAL('itemChanged'), index.internalPointer())
开发者ID:Jesonchang12,项目名称:QGIS,代码行数:14,代码来源:plugin.py
示例20: 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:LKajan,项目名称:QGIS,代码行数:50,代码来源:db_model.py
注:本文中的qgis.core.QgsDataSourceURI类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论