Sunday, 30 December 2018

Changing URI source of WMS Raster Layer in place PyQGIS


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?




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...