Message posté par : Caligraf (yoyolehmann(a)gmail.com)
----------------------------------------
Bonjour,
Je cherche à élaborer un script permettant de charger des couches issues d'une base de
donnée PostGIS. Je n'ai pour l'instant pas réussi à intégrer la classe
QgsDataSourceUri() comme je l'esperais. En effet, je tombe sur l'erreur suivante :
TypeError: invalid result from LoadLayer.processAlgorithm(), NoneType cannot be converted
to a C/C++ QVariantMap in this context
Voici le code en question :
-----------------
Code :
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingParameterString,
QgsProcessingOutputString,
QgsProcessingParameterNumber,
QgsVectorLayer,
QgsDataSourceUri,
QgsProject)
from qgis import processing
from qgis.utils import *
class LoadLayer(QgsProcessingAlgorithm):
"""
Charge une couche vectorielle depuis la base de donnée PostGIS
"""
def tr(self, string):
"""
Returns a translatable string with the self.tr() function.
"""
return QCoreApplication.translate('Processing', string)
def createInstance(self):
# Must return a new copy of your algorithm.
return LoadLayer()
def name(self):
"""
Returns the unique algorithm name.
"""
return 'load_post_gis_layer'
def displayName(self):
"""
Returns the translated algorithm name.
"""
return self.tr('Load layers from PostGIS')
def group(self):
"""
Returns the name of the group this algorithm belongs to.
"""
return self.tr('Load single vector layer')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs
to.
"""
return 'load_single_vector_layer'
def shortHelpString(self):
"""
Returns a localised short help string for the algorithm.
"""
return self.tr('Charge les couches depuis PostGIS')
def initAlgorithm(self, config=None):
"""
Here we define the inputs and outputs of the algorithm.
"""
self.addParameter(
QgsProcessingParameterString(
'HOST',
self.tr('Host'),
defaultValue = '172.16.0.116'
)
)
self.addParameter(
QgsProcessingParameterNumber(
'PORT',
self.tr('Port'),
defaultValue = 5432
)
)
self.addParameter(
QgsProcessingParameterString(
'USERNAME',
self.tr('Username'),
defaultValue = 'xyz'
)
)
self.addParameter(
QgsProcessingParameterString(
'PASSWORD',
self.tr('Password'),
defaultValue = '***'
)
)
self.addParameter(
QgsProcessingParameterString(
'DATABASE',
self.tr('Database'),
defaultValue = 'abc'
)
)
self.addParameter(
QgsProcessingParameterString(
'SCHEMA',
self.tr('schema'),
defaultValue = 'schema'
)
)
self.addParameter(
QgsProcessingParameterString(
'LAYERNAME',
self.tr('Layer name'),
defaultValue = 'Name of the layer'
)
)
self.addOutput(
QgsProcessingOutputString(
'CONNEXIONSTR',
self.tr('Imported layer')
)
)
def processAlgorithm(self, parameters, context, feedback):
host = self.parameterAsString (parameters,'HOST', context)
port = self.parameterAsString (parameters, 'PORT', context)
username = self.parameterAsString (parameters, 'USERNAME', context)
password = self.parameterAsString (parameters, 'PASSWORD',context)
database = self.parameterAsString (parameters, 'DATABASE', context)
schema = self.parameterAsString (parameters, 'SCHEMA', context)
layername = self.parameterAsString (parameters, 'LAYERNAME', context)
uri = QgsDataSourceUri()
uri.setConnection(host, port, database, username, password)
uri.setDataSource(schema, layername, "geom")
layer = QgsVectorLayer(uri.uri(), layername, "postgres")
if feedback.isCanceled():
return {}
# Return the results
return {'CONNEXIONSTR': layer}
-----------------
En poussant mes recherches, j'ai également étudié la possibilité d'ajouter une
ligne de connexion, récupérant les infos que l'on peut retrouver en cliquant sur une
couche importée dans "propriétés", en m'inspirant de cette discussion :
https://stackoverflow.com/questions/3582552/what-is-the-format-for-the-post…
-----------------
Code :
return {'CONNEXIONSTR' :
f"postgresql://{user}:{password}@{host}:{port}/{database}"}
-----------------
Toutefois ce code est incomplet, il manque des informations normalement délivrée par la
méthode setDataSource ( nom de la table, la géométrie et "postgres" ) mais
j'ignore le formatage nécessaire...
Bref, je n'ai pour l'instant pas de solution concrète, si ce n'est
éventuellement de passer par un module tiers tel que sqlalchemy par exemple.
----------------------------------------
Le message est situé
https://georezo.net/forum/viewtopic.php?pid=343471#p343471
Pour y répondre : qgis_fr(a)ml.georezo.net ou reply de votre messagerie
Pour vous désabonner connectez-vous sur le forum puis Profil / Abonnement
--
Association GeoRezo - le portail géomatique
https://georezo.net