Skip to main content
4 of 4
edited tags
Germán Carrillo
  • 37k
  • 5
  • 125
  • 180

Invalid PostgreSQL layer after loading it with PyQGIS

In a standalone PyQGIS script, I try to load a PostgreSQL (PostGIS) layer with the following code (see below).

The layer is always invalid, however when entering the code directly into the Python shell within QGIS, the layer gets loaded without any problems and is valid.

I have already checked if the credentials are valid.

I'm currently using QGIS 3.2 Desktop on Ubuntu Desktop.

#!/usr/bin/python
 # -*- coding: UTF-8 -*-

from qgis.core import *

QgsApplication.setPrefixPath("/usr/bin/qgis", True)
qgs = QgsApplication([], True)
QgsApplication.initQgis()

uri = QgsDataSourceUri()
uri.setConnection('host', '5432', 'username', 'database_name', 'password')
uri.setDataSource ('public', 'table_name', 'geometry_column_name')
uri.setKeyColumn('primary_key_column_name')
vlayer = QgsVectorLayer (uri.uri(), 'layer_name', 'postgres')
print(uri.uri())

if not vlayer.isValid():
    print("!Layer could not be loaded")
else:
    QgsProject.instance().addMapLayer(vlayer)
nbfr
  • 41
  • 3