2

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)
0

1 Answer 1

2

I found the mistake. The PrefixPath for QgsApplication was wrong. The PrefixPath that is working for me under Ubuntu is the following:

QgsApplication.setPrefixPath("/usr", True)

Not the answer you're looking for? Browse other questions tagged or ask your own question.