Message posté par : Thomas Gratier (thomas.gratier(a)gmail.com)
----------------------------------------
Bonsoir,
Une solution testée ci-dessous.
La fin est "pompée" du fichier PostGISExecuteAndLoadSQL.py dans les scripts
processing fournis avec QGIS
-----------------
Code :
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingContext,
QgsProcessingParameterString,
QgsProcessingOutputVectorLayer,
QgsProcessingOutputString,
QgsProcessingParameterNumber,
QgsVectorLayer,
QgsDataSourceUri,
QgsProject)
from qgis import processing
class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes string inputs,
to provide to DB connexion
"""
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 ExampleProcessingAlgorithm()
def name(self):
"""
Returns the unique algorithm name.
"""
return 'postgresconnexion'
def displayName(self):
"""
Returns the translated algorithm name.
"""
return self.tr('Return PostgreSQL layer')
def group(self):
"""
Returns the name of the group this algorithm belongs to.
"""
return self.tr('Example scripts')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs
to.
"""
return 'examplescripts'
def shortHelpString(self):
"""
Returns a localised short help string for the algorithm.
"""
return self.tr('Example algorithm short description')
def initAlgorithm(self, config=None):
"""
Here we define the inputs and outputs of the algorithm.
"""
# 'INPUT' is the recommended name for the main input
# parameter.
self.addParameter(
QgsProcessingParameterString(
'HOST',
self.tr('Host'),
defaultValue = 'localhost'
)
)
self.addParameter(
QgsProcessingParameterNumber(
'PORT',
self.tr('Port'),
defaultValue = 5432
)
)
self.addParameter(
QgsProcessingParameterString(
'USERNAME',
self.tr('Username'),
)
)
# 'OUTPUT' is the recommended name for the main output
# parameter.
self.addParameter(
QgsProcessingParameterString(
'PASSWORD',
self.tr('Password')
)
)
self.addParameter(
QgsProcessingParameterString(
'DATABASE',
self.tr('Database')
)
)
self.addParameter(
QgsProcessingParameterString(
'SCHEMA',
self.tr('schema'),
defaultValue = 'public'
)
)
self.addParameter(
QgsProcessingParameterString(
'LAYERNAME',
self.tr('Layer name'),
defaultValue = 'Name of the layer'
)
)
self.addOutput(
QgsProcessingOutputVectorLayer(
'LAYER',
self.tr('Vector layer'),
QgsProcessing.TypeVectorAnyGeometry
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
# First, we get the count of features from the INPUT layer.
# This layer is defined as a QgsProcessingParameterFeatureSource
# parameter, so it is retrieved by calling
# self.parameterAsSource.
host = self.parameterAsString (parameters,
'HOST',
context)
# Retrieve the buffer distance and raster cell size numeric
# values. Since these are numeric values, they are retrieved
# using self.parameterAsDouble.
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 {}
if not layer.isValid():
raise QgsProcessingException(self.tr("""This layer is invalid!
Please check the PostGIS log for error messages."""))
context.temporaryLayerStore().addMapLayer(layer)
context.addLayerToLoadOnCompletion(
layer.id(),
QgsProcessingContext.LayerDetails('SQL layer',
context.project(),
'LAYER'))
# Return the results
return {'LAYER': layer.id()}
-----------------
Vous n'êtes pas obligé de passer par la définition de chaque paramètre de la base de
données mais vous pouvez aussi réutiliser les connexions PostGIS existantes déjà définies
en passant par QgsProcessingParameterProviderConnection (toujours en regardant le fichier
PostGISExecuteAndLoadSQL.py)
Si vous souhaitez charger en une fois un ensemble de couches PostGIS en trouvant
automatiquement leur nom, vous pouvez utiliser le code de
https://gis.stackexchange.com/a/395994/638 (attention, pas dans le contexte d'un
script processing et utilisant les connexions définies dans les connexions PostgreSQL
définies dans QGIS)
Thomas
----------------------------------------
Le message est situé
https://georezo.net/forum/viewtopic.php?pid=343479#p343479
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