I've made a python function that returns the user logged in a postgis layer:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def getUser(lay, feature, parent):
    for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
        if lyr.name() == lay:
            layer = lyr
    connInfo = QgsDataSourceURI(layer.dataProvider().dataSourceUri()).connectionInfo()
    success, username, password = QgsCredentials.instance().get(connInfo, None, None)
    if success:
        return username

The problem is that the result of the function seems to be ok in the output preview when creating a new calculated field:

enter image description here

But when I check the attributes of any feature of the layer, the field is always NULL: enter image description here

Not only that but also keeps asking me to insert the credentials for the layer again and again...

The credentials are not stored in the layer so every time I open the map I am prompted to insert them. I did it just once in the beginning until now.

What am I doing wrong?

  • Did you try to save username/password in your (or the users) PostGIS connection? – Jochen Schwarze Aug 23 '16 at 12:05
  • Are you authenticating through the UI or in code somewhere? – artwork21 Aug 23 '16 at 12:06
  • As several users are accesing to this map, and some have writing permission and others only reading permission in the database for each layer, what I do is authenticate and add the layer through the UI and then I manually delete the user='xxxxx' password='xxxxx' from the datasource tag inside the layer definition in the .qgs project file. This way when the user opens the map it is asked for authentication and only does it once that works to connect all the layers. I don't know if it is the proper way of doing this, but it has worked perfectly for me until now. @artwork21 – Egidi Aug 23 '16 at 12:13
  • @JochenSchwarze No. (explanation in previous comment) – Egidi Aug 23 '16 at 12:15

Your Answer

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

Browse other questions tagged or ask your own question.