[Qgis-user] Register postgis layer using postgres service file on qgis server plugin problem

Marcos Roberto zxmarcos at gmail.com
Mon Mar 14 11:17:07 PDT 2022


Hello,

I am trying to add a new postgis layer to Qgis project using a server
plugin, if I use a connection string with "host, dbname, passwd, user" it
works flawlessly.
But I need to use pg_service file, it does not work. I thought it could be
FCGI not passing PGSERVICEFILE envvar, but it actually does. My function
register_postgis_layer simple doesn't work inside executeRequest, but it
works on ProjectService.__init__;
I tried using psycopg2 with service connection string, and it has the same
problem.

Here is sample code from my qgis server plugin.

from qgis.server import QgsService, QgsServerRequest
from qgis.core import QgsMessageLog, QgsProject,
QgsDataSourceUri, QgsVectorLayer, QgsMapLayer, QgsWkbTypes
import os

PROJECT_SQL_FILTER = 'is_deleted=false'
PROJECT_SERVICE = 'PROJECT_SERVICE'

# This works
PG_CONNECTION = f"host=localhost dbname=BDGEO user=postgres password=123456"

# This does not work
PG_CONNECTION = f"SERVICE={service}"

def register_postgis_layer(table_name):
    uri = QgsDataSourceUri()
    uri.setEncodedUri(PG_CONNECTION)
    uri.setDataSource ("public", table_name, "geom", PROJECT_SQL_FILTER)
    vlayer = QgsVectorLayer(uri .uri(False), table_name, "postgres")

    qgs_project = QgsProject.instance()
    qgs_project.addMapLayer(vlayer)
    qgs_project.write()
    return True


class ProjectService(QgsService):

    def __init__(self):
        QgsService.__init__(self)

    def name(self):
        return "PROJECTCTL"

    def version(self):
        return "1.0.0"

    def executeRequest(self, request, response, project):
        params = request.parameters()
        QgsMessageLog.logMessage(params.get('REQUEST'))

        try:
            requestMethod = params.get('REQUEST', '').upper()
            if requestMethod == 'REGISTERLAYER':
                layers = get_available_layers_for_register()
                layer_to_register = params.get('LAYER', '')
                if register_postgis_layer(layer_to_register):
                    response.write(f'Layer {layer_to_register} registered!')
                    response.setStatusCode(200)
                else:
                    response.write(f'Layer {layer_to_register} not
registered!')
                    response.setStatusCode(400)
                return
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20220314/4ea5ce7c/attachment.html>


More information about the Qgis-user mailing list