TransWikia.com

Accessing input layer when using "Selected features only" returns 'NoneType' object in QGIS 3 processing script

Geographic Information Systems Asked by PavelP on January 9, 2021

I am trying to write a processing script in QGIS 3.10.8 which would execute database function based on the selected features (or their id). I defined the input in a way that it accepts a point vector layer that the user chooses and it should then get the ids of the selected features which are used as a parameter of the database function. The problem is, that when I select some features and use "Selected features only" option, the script ends with an error:

Traceback (most recent call last):

File "string", line 119, in processAlgorithm

AttributeError: ‘NoneType’ object has no attribute ‘getFeatures’

When I don’t use "Selected features only" the script continues normally to the part where it connects to the database and executes a function. I don’t know what am I doing wrong, is there a correct way to handle the selected features of the layer?

from PyQt5.QtCore import QCoreApplication
from PyQt5.QtSql import *
from math import pow
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsFeature,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterVectorLayer,
                       QgsProcessingParameterField,
                       QgsProject,
                       QgsDataSourceUri,
                       QgsMessageLog)
import processing


class DissolveProcessingAlgorithm(QgsProcessingAlgorithm):
    """
    Dissolve algorithm that dissolves features based on selected
    attribute and summarizes the selected field by cumputing the
    sum of dissolved features.
    """

    def tr(self, string):
        """
        Returns a translatable string with the self.tr() function.
        """
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return DissolveProcessingAlgorithm()

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'points_to_line_seletion'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('Points to line with selection')

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr('Pasport_MK')

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'scripts'

    def shortHelpString(self):
        """
        Returns a localised short helper string for the algorithm. This string
        should provide a basic description about what the algorithm does and the
        parameters and outputs associated with it..
        """
        return self.tr("")

    def initAlgorithm(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        # We add the input vector features source. It can have any kind of
        # geometry.
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                'INPUT',
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorPoint]
            )
        )        

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        point_layer = self.parameterAsVectorLayer(
            parameters,
            'INPUT',
            context
        )
        
        QgsMessageLog.logMessage(context)
        
        selected_ids = []
            
        for feature in point_layer.getFeatures(): 
            selected_ids.append(feature.id)
        
        # get the underlying data provider
        provider = point_layer.dataProvider()
        if provider.name() == 'postgres':
            # get the URI containing the connection parameters
            uri = QgsDataSourceUri(provider.dataSourceUri())
            # create a PostgreSQL connection using QSqlDatabase
            db = QSqlDatabase.addDatabase('QPSQL')
            # check to see if it is valid
            if db.isValid():
                # set the parameters needed for the connection
                db.setHostName(uri.host())
                db.setDatabaseName(uri.database())
                db.setPort(int(uri.port()))
                db.setUserName(uri.username())
                db.setPassword(uri.password())                
                table_name = uri.schema() + uri.table()
                # open (create) the connection
                if db.open():
                    # execute a simple query 
                    query = db.exec_("""SELECT "MK".nearest_line_to_point(""" + 
                            table_name + """, 
                            '"MK".usek', 
                            'fk_usek'
                        )""")                    
                else:
                    err = db.lastError()
                    print (err.driverText())
        
        return {}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP