Geographic Information Systems Asked by dd_a on January 30, 2021
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 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
.
Answered by dd_a on January 30, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP