1

I wrote the code below, but I need that the PostGIS connection to be verified, to be sure that the username and password are right. I tried this: How to access user credentials in database connection? , but it didn't worked.

I am using QGIS 3.8.3

uri = QgsDataSourceUri()
uri.setConnection('LPOSTDES-CL2', '5432', 'ugpi', None, None)
connInfo = uri.connectionInfo()
(success ,user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
    QgsCredentials.instance().put(connInfo, user, passwd)
uri.setConnection('LPOSTDES-CL2', '5432', 'ugpi', user, passwd)
vitorcsm
  • 425
  • 2
  • 11
  • 1
    Replace (a, user, passwd) with (success, user, passwd), it works with me. – J. Monticolo Feb 12 '20 at 15:48
  • @J.Monticolo Thanks! Edited the post and tried again, but didn't work, because, if I enter an incorrect username or password, it doesn't return me back some error message. To see what the QGIS receive, type in the end: print(uri.connectionInfo()) – vitorcsm Feb 13 '20 at 11:01

1 Answers1

3

You can directly verify this with QtSql, see the following Python3 code :

from PyQt5.QtSql import QSqlDatabase

host = "LPOSTDES-CL2"
port = 5432
database = "ugpi"

db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName(host)
db.setPort(port)
db.setDatabaseName(database)

(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
    db.setUserName(user)
    db.setPassword(passwd)

if db.open():
    print("Connection successful !")
else:
    print("Connection failed.")

Here I just copy the method without have connInfo and there is no really reason for use QgsCredentials here, just a dialog with two QLineEdit widgets will do the stuff.

J. Monticolo
  • 15,695
  • 1
  • 29
  • 64