PyQGIS QGIS 3 – Reading WFS Layers

pyqgisqgis-3wfs

I need to read published WFS layers from QGIS Project file, but without success. I try using QgsProject.entryList() method, but only get an empty list as []:

from qgis.core import *
from PyQt5.QtCore import QFileInfo

qgs = QgsApplication([], False)

print(QgsProject.instance().entryList("WFSLayers", "/"));

qgs.exitQgis()

The WFS layers are published and show up like this in QGS project file:

<WFSLayers type="QStringList">
  <value>layer1...</value>
  <value>layer2...</value>
</WFSLayers>

Any idea what I'm doing wrong?

Best Answer

As you are in a standalone application according to your code, you need to load your qgs/qgz QGIS project file before trying to get WFS list.

At the moment, you ask to read WFS list from an empty project. So, it will always return an empty result.

from qgis.core import *
from PyQt5.QtCore import QFileInfo

qgs = QgsApplication([], False)

successfull = QGsProject.instance().read('your_path/to/your/qgis/project.qgz')
if successfull:
    print(QgsProject.instance().entryList("WFSLayers", "/"));
else:
    print("Your project wasn't loaded well")

qgs.exitQgis()

Edit: the fact to load QGIS project was only part of the solution. You need to use

print(QgsProject.instance().readListEntry('WFSLayers', '/'))

instead of

print(QgsProject.instance().entryList("WFSLayers", "/"))

Found looking at QGSProject API doc

Edit 2: Illustrations about the 6 methods readBoolEntry, readDoubleEntry, readEntry, readListEntry, subkeyList and readNumEntry to access some of the XML content within your QGIS project file.

Difference between readListEntry and entryList due to xml structure in your QGIS project (see below excerpt). Explain why QgsProject.instance().entryList("WFSLayersPrecision", "/") works and then you need QgsProject.instance().readListEntry('WFSLayers', '/').

    <WFSLayers type="QStringList">
      <value>ne_110m_populated_places_56976df7_6be4_41d8_b331_a76771b8141d</value>
    </WFSLayers>
    <WFSLayersPrecision>
      <ne_110m_admin_0_countries_d24b9f99_da2b_470c_966c_7402b525eace type="int">6</ne_110m_admin_0_countries_d24b9f99_da2b_470c_966c_7402b525eace>
      <ne_110m_populated_places_56976df7_6be4_41d8_b331_a76771b8141d type="int">6</ne_110m_populated_places_56976df7_6be4_41d8_b331_a76771b8141d>
    </WFSLayersPrecision>

You can also test the following:

  • QgsProject.instance().readNumEntry("WFSLayersPrecision", "/ne_110m_admin_0_countries_d24b9f99_da2b_470c_966c_7402b525eace"),
  • QgsProject.instance().readBoolEntry(f"WMSServiceCapabilities", "/")
  • QgsProject.instance().readDoubleEntry(f"PAL", "/CandidatesPolygonPerCM")
  • QgsProject.instance().subkeyList('DBManager', 'savedQueries') (need to save a SQL query in DB Manager to get results)
Related Question