0

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.

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Apr 12, 2019 at 15:37

1 Answer 1

3

I found the solution after observing the QGIS Plugin "Discovery" from Lutraconsulting. See here.

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', '')
 else:
 # basic (plain-text) settings
 username = settings.value('username', '', type=str)
 password = settings.value('password', '', type=str)
 return username, password
###############
 myname, mypass = get_postgres_conn_info("your_connection_name")
 print(myname)

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.

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
answered Nov 27, 2019 at 14:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.