[Qgis-developer] help with python code - works for postgis, but not for shapefiles

Ricardo Filipe Soares Garcia da ricardo.garcia.silva at gmail.com
Sun Jan 10 13:30:43 EST 2010


Hi list
I am stuck writing a part of my plugin's code. It is working fine with
postgis layers, but for some reason it doesn't work with shapefiles
I think I've managed to nail it down to the part of the code that is
not working[1].
I want this code snippet to do the following:
    - iterate over every feature of the layer
    - calculate the value of a variable called "api"
        - this variable is calculated by calling some other code and
depends on the input that the function gets from the user (hence the
call to eval in there)
    - store the "api" variable in the apiField attribute field of the layer

When the layer is a postgis layer the code works fine. When it is a
shapefile the while cycle only seems to run once, and so the "api"
variable is calculated only for the first feature. No errors are being
thrown, so I am really lost as to the cause.

If anyone can try to have a look at it and point me to what might be
the issue I'd be very thankful.
If you need to look at more of the code I've set up a project in
launchpad[2] for my plugin where you can browse the source. Look for
the fisheyefilterplugin.py file. The plugin is already functional for
the postgres provider, but I was hoping to extend it to work OGR and
spatialite providers if I could get this error fixed.

Thanks in advance

[1] - Python code follows:

def calculate_api_field(self, apiField, commands, totalCommandsToCalc):
    print "calculate_api_field method called"
    attrIndexes = self.provider.attributeIndexes()
    allFeatures = self.provider.select(attrIndexes)
    self.layer.startEditing()
    feat = QgsFeature()
    while self.provider.nextFeature(feat):
        featureId = feat.id()
        api = 0
        for command in commands.keys():
            attrName = commands[command][0]
            attrIndex = self.provider.fieldNameIndex(attrName)
            functions = apifunctions.ApiFunctions(feat,
commands[command][1:], self.provider, attrIndex)
            commandResult = eval("functions.%s()" % (command))
            if command in ("less_than", "less_than_or", "more_than",\
                           "more_than_or", "equal", "not_equal")\
                           and commandResult == 0:
                api = 0.0
                break
            api +=  commandResult
        api /= totalCommandsToCalc
        print "API:", api
        self.layer.changeAttributeValue(featureId, apiField, api)
    print "calculate_api_field method exiting"
    return self.layer.commitChanges()

[2] - http://bazaar.launchpad.net/~ricardo-garcia-silva/fisheyefilterplugin/main/files


___________________________ ___ __
Ricardo Garcia Silva


More information about the Qgis-developer mailing list