In a standalone PyQGIS script, I try to load a PostgreSQL (PostGIS) layer with the following code (see below). The
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)
#!/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)