0

I am creating an application with QGIS libraries, and in the event that the app can't add a specified layer (e.g. no connection to host, no password specified etc), it causes the app to crash, although I do get some output in the console, like QGIS displays in a message box:

credentials for dbname='testdb' host=testserver port=5432
message: fe_sendauth: no password supplied

This seems to be returned at the point where I create my QgsVectorLayer instance because the app becomes unresponsive and doesn't progress further.

My script to load the layer:

def add_postgis_vector_layer(self, username, password, layer_name, label, geometry, id):
    uri = core.QgsDataSourceURI()
    uri.setConnection(HOST, PORT, DATABASE, username, password)
    uri.setDataSource(SCHEMA, layer_name, geometry, '', id)
    layer = core.QgsVectorLayer(uri.uri(), label, 'postgres', False)  # Error message occurs at this point
    if layer.isValid():
        self.canvas.setExtent(layer.extent())
        self.canvas.zoomScale(self.canvas.scale() * 1.1)
        self.canvas.setWheelAction(2)
        # Set canvas map layers
        layers = [gui.QgsMapCanvasLayer(layer)]
        self.canvas.setLayerSet(layers)

The QApplication subclass:

class myApplication(QtGui.QApplication):
    def __init__(self, args):
        super(myApplication, self).__init__(args)
        core.QgsApplication.setPrefixPath(qgis_prefix, True)
        core.QgsApplication.initQgis()

How do I access this connection error? I can't call layer.error() (not sure if this would even work) because the app has crashed already and won't process any more code.

Edit: I'm thinking I could avoid the error by performing a query using psycopg2 with the parameters I am about to use. Still doesn't address the issue of retrieving any errors in the connection.

  • Are you doing QgsApplication.initQGis before anything else? – Nathan W Jul 5 '14 at 23:45
  • Yes It's in the __init__() of my QApplication subclass. The only thing ahead of it is QgsApplication.setPrefix(). See my edited post. Does initQgis have to come even before the QApplication is created? – James N Jul 6 '14 at 7:17

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.