QGIS data providers are written in C++, however it is possible to simulate a data provider in Python using a memory layer and some code to interface with your data.

Why would you want to do this? Typically you should use the QGIS data providers, but here are some reasons why you may want to give it a go:

  • There is no QGIS data provider
  • The generic access available through OGR doesn't provide all the features you need
  • You have no desire to write a provider in C++
  • No one will write a C++ provider for you, for any amount of money

If you go this route you are essentially creating a bridge that connects QGIS and your data store, be it flat file, database, or some other binary format. If Python can "talk" to your data store, you can write a pseudo-provider.

To illustrate the concept, we'll create a provider for CSV files that allows you to create a layer and have full editing capabilities using QGIS and the Python csv module.

The provider will:

  • Create a memory layer from a CSV file
  • Create fields in the layer based on integer, float, or string values in the CSV
  • Write changes back to the CSV file
  • Require the CSV file to have an X and Y field
  • Support only Point geometries

We'll use the cities.shp file that comes with the PyQGIS Programmer's Guide to create a CSV using ogr2ogr:

ogr2ogr -lco "GEOMETRY=AS_XY" -f CSV cities.csv ~/Downloads/pyqgis_data/cities.shp

This gives us a CSV file with point geometry fields.

If you don't want to roll your own, you can download the cities.csv file here.

Here's the header (first row) and a couple of rows from the file:

30.453327178955078,59.951889038085938,Saint Petersburg,Russia,5825000,N

Signals and Slots

We'll look at the code in a moment, but here is the general flow and connection of signals from the layer to slots (methods) in our provider:

These are all the connections we need (signal -> slot) to implement editing of both geometries and attributes for the layer.

The Plugin Code

The plugin is pretty simple; when the tool is clicked, it opens a dialog allowing you to select a CSV file, then uses the CsvLayer class to read the file, create the memory layer, make connections (signals -> slots), and add it to the QGIS canvas.

The run Method

Here's the run method from the plugin (csv_provider.py):

 1 def run(self):
 2     """Run method that performs all the real work"""
 3     # show the dialog
 4     self.dlg.show()
 5     # Run the dialog event loop
 6     result = self.dlg.exec_()
 7     # See if OK was pressed
 8     if result:
 9         csv_path = self.dlg.lineEdit.text()
10         self.csvlayer = CsvLayer(csv_path)

The dialog (csv_provider_dialog.py) contains an intimidating warning and allows you to select a CSV file to load (lines 4-6).

Line 9 gets the path of the selected file from the dialog and line 10 creates the layer using the selected file. From that point on, you interact with the layer using the regular QGIS editing tools. We need to keep a reference to the layer (self.csvlayer), otherwise all our connections get garbage collected and we lose the "link" to the CSV file.

The CsvLayer Class

The CsvLayer class manages the creation, loading, and editing of the CSV file. First let's look at the methods in csv_layer.py that create the layer from our CSV file.

Creating the Layer from the CSV

The __init__ method examines the header and a sample row to determine the names and field types to be created in the layer. To read the CSV file, we use the csv module.

Here's the __init__ method:

 1 def __init__(self, csv_path):
 2     """ Initialize the layer by reading the CSV file, creating a memory
 3     layer, and adding records to it """
 4     # Save the path to the file so we can update it in response to edits
 5     self.csv_path = csv_path
 6     self.csv_file = open(csv_path, 'rb')
 7     self.reader = csv.reader(self.csv_file)
 8     self.header = self.reader.next()
 9     logger(str(self.header))
10     # Get sample
11     sample = self.reader.next()
12     self.field_sample = dict(zip(self.header, sample))
13     logger("sample %s" % str(self.field_sample))
14     field_name_types = {}
15     # create dict of fieldname:type
16     for key in self.field_sample.keys():
17         if self.field_sample[key].isdigit():
18             field_type = 'integer'
19         else:
20             try:
21                 float(self.field_sample[key])
22                 field_type = 'real'
23             except ValueError:
24                 field_type = 'string'
25         field_name_types[key] = field_type
26     logger(str(field_name_types))
27     # Build up the URI needed to create memory layer
28     self.uri = self.uri = "Point?crs=epsg:4326"
29     for fld in self.header:
30         self.uri += '&field={}:{}'.format(fld, field_name_types[fld])
32     logger(self.uri)
33     # Create the layer
34     self.lyr = QgsVectorLayer(self.uri, 'cities.csv', 'memory')
35     self.add_records()
36     # done with the csv file
37     self.csv_file.close()
39     # Make connections
40     self.lyr.editingStarted.connect(self.editing_started)
41     self.lyr.editingStopped.connect(self.editing_stopped)
42     self.lyr.committedAttributeValuesChanges.connect(self.attributes_changed)
43     self.lyr.committedFeaturesAdded.connect(self.features_added)
44     self.lyr.committedFeaturesRemoved.connect(self.features_removed)
45     self.lyr.geometryChanged.connect(self.geometry_changed)
47     # Add the layer the map
48     QgsMapLayerRegistry.instance().addMapLayer(self.lyr)

Once the CSV file is opened, the header is read in line 8, and a sample of the first row is read in line 11.

Line 12 creates a dict that maps the field names from the header to the corresponding values in the sample row.

Line 16-25 look at each sample value and determine if its type: integer, real, or string.

Lines 28-30 create the URI needed to create the memory layer, which is done in line 34.

The add_records method is called to read the CSV and add the features in line 35.

Lastly we make the connections needed to support editing of the attribute table and the CSV file in response to the actions in our Signal/Slot diagram (lines 40-45).

Here is the add_records method that reads the CSV and creates a corresponding feature in the newly created memory layer:

 1 def add_records(self):
 2     """ Add records to the memory layer by reading the CSV file """
 3     # Return to beginning of csv file
 4     self.csv_file.seek(0)
 5     # Skip the header
 6     self.reader.next()
 7     self.lyr.startEditing()
 9     for row in self.reader:
10         flds = dict(zip(self.header, row))
11         # logger("This row: %s" % flds)
12         feature = QgsFeature()
13         geometry = QgsGeometry.fromPoint(
14             QgsPoint(float(flds['X']), float(flds['Y'])))
16         feature.setGeometry(geometry)
17         feature.setAttributes(row)
18         self.lyr.addFeature(feature, True)
19     self.lyr.commitChanges()

Each row in the CSV file is read and both the attributes and geometry for the feature are created and added to the layer.

Managing Changes

With the layer loaded and the connections made, we can edit the CSV using the regular QGIS editing tools. Here is the code for the connections that make this happen:

 1 def editing_started(self):
 2     """ Connect to the edit buffer so we can capture geometry and attribute
 3     changes """
 4     self.lyr.editBuffer().committedAttributeValuesChanges.connect(
 5         self.attributes_changed)
 7 def editing_stopped(self):
 8     """ Update the CSV file if changes were committed """
 9     if self.dirty:
10         logger("Updating the CSV")
11         features = self.lyr.getFeatures()
12         tempfile = NamedTemporaryFile(mode='w', delete=False)
13         writer = csv.writer(tempfile, delimiter=',')
14         # write the header
15         writer.writerow(self.header)
16         for feature in features:
17             row = []
18             for fld in self.header:
19                 row.append(feature[feature.fieldNameIndex(fld)])
20             writer.writerow(row)
22         tempfile.close()
23         shutil.move(tempfile.name, self.csv_path)
25         self.dirty = False
27 def attributes_changed(self, layer, changes):
28     """ Attribute values changed; set the dirty flag """
29     if not self.doing_attr_update:
30         logger("attributes changed")
31         self.dirty = True
33 def features_added(self, layer, features):
34     """ Features added; update the X and Y attributes for each and set the
35     dirty flag
36     """
37     logger("features added")
38     for feature in features:
39         self.geometry_changed(feature.id(), feature.geometry())
40     self.dirty = True
42 def features_removed(self, layer, feature_ids):
43     """ Features removed; set the dirty flag """
44     logger("features removed")
45     self.dirty = True
47 def geometry_changed(self, fid, geom):
48     """ Geometry for a feature changed; update the X and Y attributes for
49     each """
50     feature = self.lyr.getFeatures(QgsFeatureRequest(fid)).next()
51     pt = geom.asPoint()
52     logger("Updating feature {} ({}) X and Y attributes to: {}".format(
53         fid, feature['NAME'], pt.toString()))
54     self.lyr.changeAttributeValue(fid, feature.fieldNameIndex('X'),
55                                   pt.x())
56     self.lyr.changeAttributeValue(fid, feature.fieldNameIndex('Y'),
57                                   pt.y())

The dirty flag is used to indicate that the CSV file needs to be updated. Since the format doesn't support random access to individual rows, we rewrite the entire file each time an update is needed. This happens in the editing_stopped method.

When attributes are changed and/or removed, the only action taken is to set the dirty flag to True.

When there is a geometry change for a feature, it is updated in the attribute table immediately to keep the X and Y values in sync with the feature's coordinates. This happens in the geometry_changed method.

You can view the full code for both the CsvLayer class and the plugin on GitHub or by installing the plugin. To install the plugin, you'll need to make sure you have the Show also experimental plugins checkbox ticked in the Plugin Manager settings. To help you find it, the plugin is listed as CSV Provider in the Plugin Manager.

Looking Further

A few things about this implementation:

  • It is an example, not a robust implementation
  • It lacks proper error handling
  • There is no help file
  • It could be extended to support other geometry types in CSV
  • In its current form, it may not work for other CSV files, depending on how they are formatted (take a look at the Add Delimited Text Layer dialog in QGIS to see what I mean)
  • If you want to enhance this for fun or profit---well for fun, fork the repository and give me some pull requests

A couple of final points:

  • Going this route can be a lot more work than using an existing data provider
  • This method can be (and has been) used successfully to interface with a data store for which there is no data provider