I'm trying to establish a Postgres connection using QgsCredentials as described here:
How to access user credentials in database connection?
The only problem is that I cannot establish a working connection unless I "physically" add the layer to the map canvas (which I don't want because I only want a connection to the DB and a reference to the layer which will be edited later on in the code)
When clicking a button the run function reads:
uri = QgsDataSourceURI()
connInfo = uri.connectionInfo()
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
# Isn't this enough to establish the connection and get a valid reference to the layer?
uri.setConnection("HOST", "PORT", "DB_NAME", user, passwd)
uri.setDataSource("SCHEMA", "TABLE_NAME", "the_geom")
LYR = QgsVectorLayer(uri.uri(), "LYR", "postgres")
# Unless I add the following line, I am not able to use properly the object
# (which asks the user the credentials until he/she inserts the right ones and gets
# a working connection with a valid reference to the layer)
QgsMapLayerRegistry.instance().addMapLayer(LYR)
What am I doing wrong?
Thanks in advance,
m.
Answer
The problem is that you are trying to fetch credentials for an empty URI. When you query the credentials store you need to supply it with the information, for which connection you need to get the credentials. If you update the code as follows you will get the expected result:
uri = QgsDataSourceURI()
# assign this information before you query the QgsCredentials data store
uri.setConnection("HOST", "PORT", "DB_NAME", None, None)
connInfo = uri.connectionInfo()
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
uri.setPassword(passwd)
uri.setUsername(user)
uri.setDataSource("SCHEMA", "TABLE_NAME", "the_geom")
LYR = QgsVectorLayer(uri.uri(), "LYR", "postgres")
# Work with the layer (E.g. get feature count...)
len( list( LYR.getFeatures() ) )
No comments:
Post a Comment