1

In my Qgis Plugin, I manage a set of WMS layers that are secured by Api key. As I develop this plugin for differents clients who have different Api Key, I need to set the right Key when a specific client connect to the plugin. As I can change the DataSource of a vector Layer without reloading it and keeping it in place in the project with the setDataSource() method of QgsVectorLayer, I wonder if I can do the same with a QgsRasterLayer. I can't find a method in Api docs.

For now my workaround is to remove all my WMS Layer and reload it from scratch with the right Api Key. For me it's not optimal because it doesn't keep the layer tree clean... (layer order, groups,...) and it takes time...

Here is the code that I actually use:

layers = [layer for layer in QgsMapLayerRegistry.instance().mapLayers().values() if layer.name() in all_flux_provider]
# all_flux_provider is the list of WMS layer that I manage
        for layer in layers:
            # remove all managed flux
            QgsMapLayerRegistry.instance().removeMapLayer(layer.id())
        #Add client layers from scratch
        for flux in fluxs: # fluxs is a list of dict that represent the WMS layer of the client (it comes from a database). structured like that:
                           #{key:apikey of the client, provider:name of the flux provider, url:uri to load the flux}
                layer = None
                if '{insee}' in flux['url']: # {insee} is a placeholder in the url of the flux
                    for insee in insees:
                        uri = flux['url'].strip().format(insee=insee)
                        layer = QgsRasterLayer(uri, flux['provider']+'_'+str(insee), 'wms')
                        QgsMapLayerRegistry.instance().addMapLayer(layer)
                elif '{client_key}' in flux['url']: #{client_key} is a placeholder in the url of the flux
                    uri = flux['url'].strip().format(client_key=flux['key'])
                    layer = QgsRasterLayer(uri, flux['provider'], 'wms')
                    QgsMapLayerRegistry.instance().addMapLayer(layer)

Does anyone know a better way or a good trick to achieve this?

  • (Stumbling across this). Would examining the source code of the changeDataSource plugin help? It changes the URI of both vector and raster layers based on user input. – Houska Apr 8 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.