I've been trying to get the username of a PostgreSQL connection in QGIS 3.6, using this Python code

layer = iface.activeLayer()
provider = layer.dataProvider()
username = QgsDataSourceUri(provider.dataSourceUri()).username()
print (username)

like in this question Getting active PostgreSQL connection's username as variable in QGIS?

It does give me an empty string and I think it is because the connection uses an authentication configuration, so the username is not available this way. Is there another way ? I found the QgsAuthManager class but as a newbie I really can't figure out what to do with it.


I answer my own question because I found the solution after observing the QGis Plugin "Discovery" from Lutraconsulting. See here : https://github.com/lutraconsulting/qgis-discovery-plugin/blob/master/Discovery/dbutils.py

The code is :

def get_postgres_conn_info(selected):
""" Read PostgreSQL connection details from QSettings stored by QGIS
settings = QSettings()
settings.beginGroup(u"/PostgreSQL/connections/" + selected)
if not settings.contains("database"): # non-existent entry?
    return {}

conn_info = dict()
conn_info["host"] = settings.value("host", "", type=str)

# password and username
username = ''
password = ''
authconf = settings.value('authcfg', '')
if authconf :
    # password encrypted in AuthManager
    auth_manager = QgsApplication.authManager()
    conf = QgsAuthMethodConfig()
    auth_manager.loadAuthenticationConfig(authconf, conf, True)
    if conf.id():
        username = conf.config('username', '')
        password = conf.config('password', '')
    # basic (plain-text) settings
    username = settings.value('username', '', type=str)
    password = settings.value('password', '', type=str)

And as one can see they test for the two password storing possibilities and retrieve the login and password from the one that is used, after searching inside the QSettings.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.