Saturday, 29 July 2017

qgis - Retrieve available PostGIS connections in PyQGIS


Can I retrieve the available connections to PostGIS databases in PyQGIS? I would like to provide a list of available db-connections, and subsequently a list of tables within the ui of my plugin.


I checked the cookbook but cannot find a way to get further with this.



Answer



To get the information you want, you need to use the QSettings class. This uses a hierarchical structure, like the Windows registry. If you have the latest version of QGIS, you can see this hierarchy using Settings>Options>Advanced


The following code works from the Python Console. I've not tried this from a plugin or outside of QGIS, so some additional work might be required in these cases.


To see the hierarchy, use this in the QGIS python console...


from PyQt4.QtCore import QSettings

qs = QSettings()
for k in sorted(qs.allKeys())
print k

The output gives some hints...


.. snip ..
Plugins/searchPathsForPlugins
Plugins/valuetool/mouseClick
PostgreSQL/connections/GEODEMO/allowGeometrylessTables
PostgreSQL/connections/GEODEMO/database

PostgreSQL/connections/GEODEMO/dontResolveType
PostgreSQL/connections/GEODEMO/estimatedMetadata
.. snip ...

So you can get database connection details by filtering for the prefix PostgreSQL/Connections/


So in this case I have a connection called GEODEMO, I can get the username like so...


from PyQt4.QtCore import QSettings
qs = QSettings()
print qs.value("PostgreSQL/connections/GEODEMO/username")
>> steven


Once you have a database in mind, you can retrieve a list of tables using the PostGisDBConnector class.


import db_manager.db_plugins.postgis.connector as con
from qgis.core import QgsDataSourceURI

uri = QgsDataSourceURI()
uri.setConnection("127.0.0.1", "5432", "database_name", "username", "password")
c = con.PostGisDBConnector(uri)
print c
print c.getTables()


Note that the port should be a string, not a number.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...