TransWikia.com

Access SpatiaLite connections with PyQGIS QgsProviderMetadata (QGIS 3.10.7 LTR)

Geographic Information Systems Asked on November 1, 2021

I would like to list spatialite connections and access a specific connectionwith PyQGIS. For postgres provider it’s pretty straightforward:

>>> QgsProviderRegistry.instance().providerMetadata('postgres').connections()
{'alkis (authcfg)': <qgis._core.QgsAbstractDatabaseProviderConnection object at 0x000001D663232CA8>, 'baumradar (authcfg)': <qgis._core.QgsAbstractDatabaseProviderConnection object at 0x000001D663232948>, 'eb77 (authcfg)': <qgis._core.QgsAbstractDatabaseProviderConnection object at 0x000001D663232E58>,...
>>> QgsProviderRegistry.instance().providerMetadata('postgres').connections()['alkis (authcfg)']
<qgis._core.QgsAbstractDatabaseProviderConnection object at 0x000001D663232CA8>

But the same thing for spatialite provider returns a traceback:

>>> QgsProviderRegistry.instance().providerMetadata('spatialite').connections()
Traceback (most recent call last):
  File "C:OSGEO4~1appsPython37libcode.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
_core.QgsProviderConnectionException: Provider spatialite has no connections method

Same problem with e.g. wms provider, both are available:

>>> QgsProviderRegistry.instance().providerList()
['DB2', 'WFS', 'arcgisfeatureserver', 'arcgismapserver', 'delimitedtext', 'gdal', 'geonode', 'gpx', 'mdal', 'memory', 'mesh_memory', 'mssql', 'ogr', 'ows', 'postgres', 'spatialite', 'virtual', 'wcs', 'wms']

Shouldn’t all providers accessed through QgsProviderMetadata()? How to list and access spatialite (and other) connections using this class?

One Answer

You're right. It seems that, in the future, all data providers will be fully implemented in that way (known as Connections API). Nowadays, some providers are not there yet. Even more if you're not using the cutting edge of QGIS versions.

FYI, running on QGIS master (built today), I can perfectly access SpatiaLite connections in the expected way:

QgsProviderRegistry.instance().providerMetadata('spatialite').connections()

In the meantime, there is a workaround for your use case, using QSettings.

List connections:

settings = QSettings()
settings.beginGroup('/SpatiaLite/connections/')
connections = settings.childGroups()
settings.endGroup()
print(connections)

Get selected connection's db path:

selectedConnection = settings.value( '/SpatiaLite/connections/selected', '' , type=str)
if selectedConnection:
    dbpath = settings.value( '/SpatiaLite/connections/{}/sqlitepath'.format(selectedConnection), '' , type=str)
    print(dbpath)

More details about Connections API: https://www.itopen.it/qgis-abstract-connections-api/

Answered by Germán Carrillo on November 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP