[GIS] How to get User and Password of a PostGIS layer from PyQGIS

postgispyqgisqgis

I wonder if it is possible to get the user and password for a PostGIS database if they are stored in the PostGis connection information.

I get the connection information at the moment from the active layer like this:

connInfo = QgsDataSourceURI(layer.dataProvider().dataSourceUri()).connectionInfo()
print connInfo
dbname='test_geodata_project' host=10.0.4.111 port=5432 sslmode=disable

userInfo = QgsCredentials.instance().get(connInfo, None, None)
print userInfo
(True, u'testuser', 'test')

But the user has to type in the user/password manually. Is there something like the connectionInfo() but with user/password?

Best Answer

Yes, you can do that, but only if you chose to save user and password while establishing the PostGIS connection.

enter image description here

If you did so and your active layer is a PostGIS layer, you can access the connection information this way:

layer = iface.activeLayer()
source = layer.source()
print source

You'll get a key-value string like this:

dbname='mydb' host=localhost port=5432 user='myuser' password='mypassword' sslmode=disable key='gid' srid=4326 type=MULTIPOLYGON table="public"."mytable" (geographicextent) sql=

From which you can obtain the password this way:

kvp = source.split(" ")
for kv in kvp:
    if kv.startswith("password"):
        thePassword = kv.split("=")[1][1:-1]
        print thePassword

Include a similar if for the user into the for loop and you are done.

Related Question