def from_xml(layers): """ Derives temporal information from a Capabilities XML file on disk :param mapfile: filepath to Capabilities XML on disk :param layers: `list` of layer names :returns: `dict` of layer temporal configuration """ if GEOMET_MAPPROXY_CACHE_XML is None: raise RuntimeError('GEOMET_MAPPROXY_CACHE_XML not set') ltu = {} LOGGER.debug('Reading global WMS Capabilities XML from disk') with open(GEOMET_MAPPROXY_CACHE_XML, 'rb') as fh: xml = fh.read() wms = WebMapService('url', version='1.3.0', xml=xml) for layer in layers: dimensions_list = ['time', 'reference_time'] for dimension in dimensions_list: if dimension in wms[layer].dimensions.keys(): if layer not in ltu.keys(): ltu[layer] = {} ltu[layer][dimension] = { 'default': wms[layer].dimensions[dimension]['default'], 'values': wms[layer].dimensions[dimension]['values'] } return ltu
def test_getmap_130_national_map(): """National Map""" # TODO: use flaky tests or fix it: https://pypi.python.org/pypi/pytest-ignore-flaky url = SERVICE_URL_NATIONAL_MAP wms = WebMapService(url, version='1.3.0') rsp = wms.getmap( layers=['3'], styles=['default'], srs='CRS:84', bbox=(-176.646, 17.7016, -64.8017, 71.2854), size=(500, 300), format='image/png', transparent=True) assert type(rsp) is ResponseWrapper assert "service=WMS" in wms.request assert "version=1.3.0" in wms.request assert "request=GetMap" in wms.request assert "layers=3" in wms.request assert "styles=default" in wms.request assert "crs=CRS%3A84" in wms.request assert "box=-176.646%2C17.7016%2C-64.8017%2C71.2854" in wms.request assert "width=500" in wms.request assert "height=300" in wms.request assert "format=image%2Fpng" in wms.request assert "transparent=TRUE" in wms.request
def test_wms_style_looping_getmap(ows_server): # Use owslib to confirm that we have a somewhat compliant WMS service wms = WebMapService(url=ows_server.url + "/wms", version="1.3.0", timeout=120) # Ensure that we have at least some layers available contents = list(wms.contents) test_layer_name = contents[0] test_layer = wms.contents[test_layer_name] test_layer_styles = wms.contents[test_layer_name].styles bbox = test_layer.boundingBoxWGS84 layer_bbox = pytest.helpers.enclosed_bbox(bbox) layer_time = test_layer.timepositions[len(test_layer.timepositions) // 2].strip() for style in test_layer_styles: img = wms.getmap( layers=[test_layer_name], styles=[style], srs="EPSG:4326", bbox=layer_bbox, size=(150, 150), format="image/png", transparent=True, time=layer_time, ) assert img.info()["Content-Type"] == "image/png"
def retreive_WMS_metadata(layername): url = settings.OGC_SERVER['default'][ 'LOCATION'] + "geonode/" # workspace is hard-coded in the importer url += layername + "/wms?request=GetCapabilities&version=1.1.1" get_cap_data = CreateStoryLayerThumbnailTask.request_geoserver_with_credentials( url) wms = WebMapService(url, xml=get_cap_data) # I found that some dataset advertise illegal bounds - fix them up xmin = wms[layername].boundingBoxWGS84[0] if math.isnan(xmin) or math.isinf(xmin) or xmin < -180: xmin = -180 ymin = wms[layername].boundingBoxWGS84[1] if math.isnan(ymin) or math.isinf(ymin) or ymin < -90: ymin = -90 xmax = wms[layername].boundingBoxWGS84[2] if math.isnan(xmax) or math.isinf(xmax) or xmax > 180: xmax = 180 ymax = wms[layername].boundingBoxWGS84[3] if math.isnan(ymax) or math.isinf(ymax) or ymax > 90: ymax = 90 return [xmin, ymin, xmax, ymax], wms[layername].timepositions
def test_ncwms2(): """Test with an ncWMS2 server. """ # Note that this does not exercise the bug in https://github.com/geopython/OWSLib/issues/556 wms = WebMapService(NCWMS2_URL, version='1.3.0') rsp = wms.getmap( layers=['f33_thredds/min_temp'], styles=['default'], srs='CRS:84', bbox=(-124.17, 46.02, -123.29, 46.38), size=(256, 256), format='image/png', transparent=True, mode='32bit', ) assert type(rsp) is ResponseWrapper assert "service=WMS" in wms.request assert "version=1.3.0" in wms.request assert "request=GetMap" in wms.request assert "layers=f33_thredds/min_temp" in wms.request assert "styles=default" in wms.request assert "crs=CRS%3A84" in wms.request assert "width=256" in wms.request assert "height=256" in wms.request assert "format=image%2Fpng" in wms.request assert "transparent=TRUE" in wms.request
def __init__(self, url, version="1.1.1"): self.wms = WebMapService(url, version=version) self.type = self.wms.identification.type self.version = self.wms.identification.version self.title = self.wms.identification.title self.abstract = self.wms.identification.abstract self.size = (256, 256)
def validate_wms(self) -> None: """Validate input arguments with the WMS service.""" wms = WebMapService(self.url, version=self.version) if not isinstance(self.layers, (str, list)): raise InvalidInputType("layers", "str or list") layers = [self.layers] if isinstance(self.layers, str) else self.layers valid_layers = { wms[lyr].name: wms[lyr].title for lyr in list(wms.contents) } if any(lyr not in valid_layers.keys() for lyr in layers): raise InvalidInputValue("layers", (f"{n} for {t}" for n, t in valid_layers.items())) valid_outformats = wms.getOperationByName("GetMap").formatOptions if self.outformat not in valid_outformats: raise InvalidInputValue("outformat", valid_outformats) valid_crss = { lyr: [s.lower() for s in wms[lyr].crsOptions] for lyr in layers } if any(self.crs not in valid_crss[lyr] for lyr in layers): _valid_crss = (f"{lyr}: {', '.join(cs)}\n" for lyr, cs in valid_crss.items()) raise InvalidInputValue("CRS", _valid_crss)
def connectToServer(self, noInternet=False): if noInternet is False: try: print('connecting to server') # open connection to get JSON traffic data self.__wfs = WebFeatureService( url='http://api.vicroads.vic.gov.au/vicroads/wfs?' + self.__APItoken, version='1.1.0', username=None, password=None, ) # open connection to get map tiles with traffic lines self.__wms = WebMapService( 'http://api.vicroads.vic.gov.au/vicroads/wms?' + self.__APItoken, version='1.1.1', username=None, password=None, ) except ReadTimeout: print('request timeout') else: print( "no internet connection, will load old data from file instead")
def connectToDG(config): return WebMapService( "https://evwhs.digitalglobe.com/mapservice/wmsaccess?connectid=" + config['connectid'], username=config['uname'], password=config['passwd'], version='1.1.1')
def updateCap(request): # This update the DB not sure why. it should be deleted (or not) GetCapapilities.objects.all().delete() from owslib.wms import WebMapService url = request.GET.get("source", "http://geo.weather.gc.ca/geomet-beta") wms = WebMapService(url, timeout=300) wmsl = list(wms.contents) for la in wmsl: try: if wms.contents[la].timepositions is not None: timeE = True timeEx = wms.contents[la].timepositions[0] else: timeE = False timeEx = "" except: timeE = False s = GetCapapilities(source=url, prodName=la, timeEnabled=timeE, timeExtent=timeEx) s.save() text = "" for sou in GetCapapilities.objects.all(): text += sou.source + "\t" + sou.prodName + "\t" + str( sou.timeEnabled) + "\t" + sou.timeExtent + "\r\n" return HttpResponse(text)
def test_wms_130_remotemd_parse_single(self, mp_wms_130): """Test the remote metadata parsing for WMS 1.3.0. Tests parsing the remote metadata for a single layer. Test whether the method is available and returns remote metadata if MetadataURLs are available in the GetCapabilities. Parameters ---------- mp_wms_130 : pytest.fixture Monkeypatch the call to the remote GetCapabilities request. """ wms = WebMapService(url='http://localhost/not_applicable', version='1.3.0', parse_remote_metadata=False) assert 'meetnetten' in wms.contents layer = wms.contents['meetnetten'] layer.parse_remote_metadata() mdrecords = layer.get_metadata() assert type(mdrecords) is list assert len(mdrecords) == 1 for m in mdrecords: assert type(m) is owslib.iso.MD_Metadata
def updateALayer(request): # This update the information about a layer in the DB sourceToUpdate = request.GET.get("source", "") layerToUpdate = request.GET.get("name", "") if (sourceToUpdate == "") or (layerToUpdate == ""): return HttpResponseNotFound('') else: from owslib.wms import WebMapService # Delete old files GetCapapilities.objects.filter(source=sourceToUpdate, prodName=layerToUpdate).delete() wms = WebMapService(sourceToUpdate, timeout=300) wmsl = list(wms.contents) try: if wms.contents[layerToUpdate].timepositions is not None: timeE = True timeEx = wms.contents[layerToUpdate].timepositions[0] else: timeE = False timeEx = "" except: timeE = False s = GetCapapilities(source=sourceToUpdate, prodName=layerToUpdate, timeEnabled=timeE, timeExtent=timeEx, lastUpdate=timezone.now()) s.save() return HttpResponse("done")
def updateASource(request): # This is supposed to update the information about a source in the # DB. Write now it just delete the information and regenerate it # (not great but actually works) sourceToUpdate = request.GET.get("source", "") if sourceToUpdate == "": return HttpResponseNotFound('') else: from owslib.wms import WebMapService # Delete old files GetCapapilities.objects.filter(source=sourceToUpdate).delete() t = Source.objects.get(source=sourceToUpdate) t.lastUpdate = timezone.now() t.save() wms = WebMapService(sourceToUpdate, timeout=300) wmsl = list(wms.contents) for la in wmsl: try: if wms.contents[la].timepositions is not None: timeE = True timeEx = wms.contents[la].timepositions[0] else: timeE = False timeEx = "" except: timeE = False s = GetCapapilities(source=sourceToUpdate, prodName=la, timeEnabled=timeE, timeExtent=timeEx, lastUpdate=timezone.now()) s.save() return HttpResponse("done")
def from_wms(layers=[]): """ Derives temporal information from a WMS :param layers: :param layers: `list` of layer names :returns: `dict` of layer temporal configuration """ if GEOMET_MAPPROXY_CACHE_WMS is None: raise RuntimeError('GEOMET_MAPPROXY_CACHE_WMS not set') ltu = {} for layer in layers: LOGGER.debug('Requesting WMS Capabilities for layer: {}'.format(layer)) url = '{}?layer={}'.format(GEOMET_MAPPROXY_CACHE_WMS, layer) wms = WebMapService(url, version='1.3.0') dimensions_list = ['time', 'reference_time'] for dimension in dimensions_list: if dimension in wms[layer].dimensions.keys(): if layer not in ltu.keys(): ltu[layer] = {} ltu[layer][dimension] = { 'default': wms[layer].dimensions[dimension]['default'], 'values': wms[layer].dimensions[dimension]['values'] } return ltu
def service(self): if self.service_type == 'WMS': return WebMapService(self.url, self.version) elif self.service_type == 'WFS': return WebFeatureService(self.url, self.version) else: raise ValueError('Service not supported')
def test_ows_interfaces_wms(): wmsxml = open(resource_file('wms_JPLCapabilities.xml'), 'rb').read() service = WebMapService('url', version='1.1.1', xml=wmsxml) # Check each service instance conforms to OWSLib interface service.alias = 'WMS' isinstance(service, owslib.map.wms111.WebMapService_1_1_1) # URL attribute assert service.url == 'url' # version attribute assert service.version == '1.1.1' # Identification object assert hasattr(service, 'identification') # Check all ServiceIdentification attributes assert service.identification.type == 'OGC:WMS' for attribute in ['type', 'version', 'title', 'abstract', 'keywords', 'accessconstraints', 'fees']: assert hasattr(service.identification, attribute) # Check all ServiceProvider attributes for attribute in ['name', 'url', 'contact']: assert hasattr(service.provider, attribute) # Check all operations implement IOperationMetadata for op in service.operations: for attribute in ['name', 'formatOptions', 'methods']: assert hasattr(op, attribute) # Check all contents implement IContentMetadata as a dictionary isinstance(service.contents, OrderedDict) # Check any item (WCS coverage, WMS layer etc) from the contents of each service # Check it conforms to IContentMetadata interface # get random item from contents dictionary -has to be a nicer way to do this! content = service.contents[list(service.contents.keys())[0]] for attribute in ['id', 'title', 'boundingBox', 'boundingBoxWGS84', 'crsOptions', 'styles', 'timepositions']: assert hasattr(content, attribute)
def capcache_query(self): self.capcache_tstamp = datetime.utcnow() reader = WMSCapabilitiesReader(self.version, url=self.url, un=self.username, pw=self.password, headers=env.wmsclient.headers) self.capcache_xml = etree.tostring(reader.read(self.url)) service = WebMapService( url=self.url, version=self.version, username=self.username, password=self.password, xml=str(self.capcache_xml)) layers = [] for lid, layer in service.contents.iteritems(): layers.append(OrderedDict(( ('id', lid), ('title', layer.title), ('index', map(int, layer.index.split('.'))), ))) layers.sort(key=lambda i: i['index']) for l in layers: del l['index'] data = OrderedDict(( ('formats', service.getOperationByName('GetMap').formatOptions), ('layers', layers))) self.capcache_json = json.dumps(data, ensure_ascii=False)
def request(self, service): try: if service == 'WMS': self.resp['resp'] = WebMapService( "https://data.linz.govt.nz/services;" "key=" + self.key + "/wms/", version='1.1.1') return if service == 'WMTS': self.resp['resp'] = WebMapTileService( "https://data.linz.govt.nz/services;" "key=" + self.key + "/wmts/1.0.0/WMTSCapabilities.xml?" "count=10", version='1.0.0') return if service == 'WFS': self.resp['resp'] = WebFeatureService( "https://data.linz.govt.nz/services;" "key=" + self.key + "/wfs/?" "service=WFS&" "request=GetCapabilities", version='1.1.0') return except: self.resp[ 'err'] = "ERROR: Something went wrong with the request. Timeout? Incorrect API KEY?"
def createWmsSource(self, params): name = params['name'] baseURL = params['baseURL'] parsedUrl = getUrlParts(baseURL) hostName = parsedUrl.netloc username = params['username'] if 'username' in params else None password = params['password'] if 'password' in params else None wms = WebMapService(baseURL, version='1.1.1', username=username, password=password) layersType = list(wms.contents) layers = [] source = self._sourceMetadata(username, password, baseURL, hostName) source['layer_source'] = name for layerType in layersType: dataset = self.createWmsDataset(source, params={ 'typeName': layerType, 'name': wms[layerType].title, 'abstract': wms[layerType].abstract}) layers.append(dataset) return layers
def get_wms_image_size(self,layer_name,srs,min_x,min_y,max_x,max_y): """ Get the size of the png image returned for the current service url | set service url | ${WMS_URL} | | ${image_size_in_kb} | get wms image size | bathymetry | EPSG:4326 | -112 | 55 | -106 | 71 | | ${greater_than_5kb} | ${image_size_in_kb} > 5 | | Should Be True | ${greater_than_5kb} | returns an integer which is the size of the image in kB """ wms = WebMapService(self._url,version=self._ogc_version) img = wms.getmap( layers = [layer_name], srs=srs, bbox=(float(min_x),float(min_y),float(max_x),float(max_y)),size=(300,300),format='image/png') out = open('test.png','wb') out.write(img.read()) out.close() f = open('test.png','rb') size = os.path.getsize('test.png') / 1024 f.close() os.remove('test.png') return int(math.ceil(size))
def test_wms_getfeatureinfo_130(): wms = WebMapService(SERVICE_URL, version='1.3.0') res1 = wms.getfeatureinfo( layers=['bvv:lkr_ex'], srs='EPSG:31468', bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg', info_format="text/html", xy=(250, 250)) html_string1 = res1.read().decode("utf-8") assert 'lkr_ex' in html_string1 assert 'gmd_ex' in html_string1 res2 = wms.getfeatureinfo( layers=['bvv:lkr_ex', 'bvv:gmd_ex'], srs='EPSG:31468', bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg', info_format="text/html", xy=(250, 250)) html_string2 = res2.read().decode("utf-8") assert 'lkr_ex' in html_string2 assert 'gmd_ex' in html_string2 res3 = wms.getfeatureinfo( layers=['bvv:lkr_ex', 'bvv:gmd_ex'], srs='EPSG:31468', bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg', query_layers=['bvv:lkr_ex'], info_format="text/html", xy=(250, 250)) html_string3 = res3.read().decode("utf-8") assert 'lkr_ex' in html_string3 assert 'gmd_ex' not in html_string3
def test_wms_getlegendgraphic(ows_server): # Use owslib to confirm that we have a somewhat compliant WMS service wms = WebMapService(url=ows_server.url + "/wms", version="1.3.0") # Ensure that we have at least some layers available contents = list(wms.contents) test_layer_name = contents[0] test_layer_styles = wms.contents[test_layer_name].styles for style in test_layer_styles: # check if this layer has a legend legend_url = test_layer_styles[style].get("legend") url = ows_server.url + "/wms" resp = requests.get( url, allow_redirects=False, params={ "request": "GetLegendGraphic", "layer": test_layer_name, "version": "1.3.0", "service": "WMS", "styles": style, "format": "image/png", }, ) if legend_url: assert resp.headers.get("content-type") == "image/png" assert resp.status_code == 200 else: assert resp.status_code == 404
def getmap_url_generator(): getmap_urls = [] stable_url = request.get_json() wms = WebMapService(url=stable_url + "/wms", version="1.3.0", timeout=120) contents = list(wms.contents) for layer in contents: test_layer_name = layer test_layer = wms.contents[test_layer_name] time = "" bbox = test_layer.boundingBoxWGS84 layers_url_list = [] fixed_espg = "EPSG%3A3857" fixed_bbox = "15028131.257091936%2C-2504688.542848654%2C15654303.392804097%2C-1878516.4071364924" if test_layer.timepositions: time = test_layer.timepositions[len(test_layer.timepositions) // 2].strip() for style in test_layer.styles: print(time, file=sys.stdout) url = f"{stable_url}wms?service=WMS&version=1.3.0&request=GetMap&layers={test_layer_name}&styles={style}&width=250&height=250&crs={fixed_espg}&bbox={fixed_bbox}&format=image%2Fpng&transparent=TRUE&bgcolor=0xFFFFFF&exceptions=XML&time={time}" layers_url_list.append({"style": style, "url": url}) getmap_urls.append({ "name": test_layer_name, "layersList": layers_url_list }) # return jsonify(getmap_urls) return json.dumps(getmap_urls)
def add_to_axes(ax,fig,crs_df,params_WMS={},zorder=2): """ """ from owslib.wms import WebMapService import io import matplotlib.image as mpimg xmin, xmax, ymin, ymax = ax.axis() bbox_to_wms=(xmin,ymin,xmax,ymax) print(bbox_to_wms) #calculando tamaño del axes en pixeles bbax=ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) size_px=bbax.width * fig.dpi, bbax.height*fig.dpi size_px=tuple([int(round(n)) for n in size_px]) #print(size_px) urlWms=params_WMS["url"] srsWms=params_WMS["srs"] layersWms= params_WMS["layers"] layers_transparent= params_WMS["transparent"] if "transparent" in params_WMS else True layers_format= params_WMS["format"] if "format" in params_WMS else "image/png" wms=WebMapService(urlWms,version="1.1.1") #print(list(wms.contents)) #print(crs_df.upper(),srsWms) if crs_df.upper() != srsWms.upper(): from pyproj import Proj, transform print("reproyectando bounds de wms") dfProj = Proj(init=crs_df.lower()) wmsProj = Proj(init=srsWms.lower()) xmin_WMS,ymin_WMS=transform(dfProj,wmsProj,xmin,ymin) xmax_WMS,ymax_WMS=transform(dfProj,wmsProj,xmax,ymax) bbox_to_wms=(xmin_WMS,ymin_WMS,xmax_WMS,ymax_WMS) img=wms.getmap(layers=layersWms,srs=srsWms,bbox=bbox_to_wms ,format=layers_format,size=size_px,transparent=layers_transparent) i=io.BytesIO(img.read()) i=mpimg.imread(i,format="png") ax.imshow(i,extent=[xmin,xmax,ymin,ymax],zorder=zorder)
def wms_interrogate(server_name): """ Find what WMS options exist for a given WMS server. The user must be able to construct a WMS request from this information. Args: * server - WMS server url Returns: a :class:`WmsInfo` object containing the interrogation results. Example :: server = "http://wms.jpl.nasa.gov/wms.cgi" wms_info = wms_interrogate(server) print wms_info The results can also be printed with all the layer projection attributes :: print wms_info.verbose() .. TIP: Please see the documentation for :func:`WmsSummary.verbose` for potentially important information regarding verbose output. """ result = None # Get the service. wms = WebMapService(server_name) if "WMS" in wms.identification.type: result = WmsSummary(server_name, wms.identification.title) # Get every layer. for layer_label, layer in wms.contents.items(): result.layers.append( _WmsLayerSummary(layer_label, layer.title, layer.styles.keys())) # Get every projection for this layer. for crs in layer.crsOptions: # Get attributes of the projection result.layers[-1].projections[crs] = attrs = {} for attr_name in dir(layer): if attr_name.startswith("__"): continue if attr_name in ["name", "parent"]: continue attrs[attr_name] = getattr(layer, attr_name) else: return "Unhandled type: {}".format(wms.identification.type) return result
def assert_wms_layer(workspace, layername, exp_title): wms = WebMapService(gs_wms.get_wms_url(workspace), gs_wms.VERSION) assert layername in wms.contents wms_layer = wms[layername] assert wms_layer.title == exp_title assert_non_empty_bbox(wms_layer.boundingBox) assert_non_empty_bbox(wms_layer.boundingBoxWGS84) return wms_layer
def get_wms(version='1.1.1', type_name=None, username=None, password=None): """ Function to return an OWSLib WMS object """ # right now owslib does not support auth for get caps # requests. Either we should roll our own or fix owslib if type_name: url = GEOSERVER_URL + \ '%swms?request=getcapabilities' % type_name.replace(':', '/') else: url = GEOSERVER_URL + \ 'wms?request=getcapabilities' if username and password: return WebMapService(url, version=version, username=username, password=password) else: return WebMapService(url)
def get_metadata(self, resource, version='1.1.1'): """ Get metadata, specific per Resource type. :param resource: :param version: :return: Metadata object """ return WebMapService(resource.url, version=version)
def _process_wms_service(url, name, type, username, password, wms=None, owner=None, parent=None): """ Create a new WMS/OWS service, cascade it if necessary (i.e. if Web Mercator not available) """ if wms is None: wms = WebMapService(url) try: base_url = _clean_url( wms.getOperationByName('GetMap').methods['Get']['url']) if base_url and base_url != url: url = base_url wms = WebMapService(base_url) except: logger.info( "Could not retrieve GetMap url, using originally supplied URL %s" % url) pass try: service = Service.objects.get(base_url=url) return_dict = [{'status': 'ok', 'msg': _("This is an existing service"), 'service_id': service.pk, 'service_name': service.name, 'service_title': service.title }] return HttpResponse(json.dumps(return_dict), mimetype='application/json', status=200) except: pass title = wms.identification.title if not name: if title: name = _get_valid_name(title) else: name = _get_valid_name(urlsplit(url).netloc) try: supported_crs = ','.join(wms.contents.itervalues().next().crsOptions) except: supported_crs = None if supported_crs and re.search('EPSG:900913|EPSG:3857|EPSG:102100|EPSG:102113', supported_crs): return _register_indexed_service(type, url, name, username, password, wms=wms, owner=owner, parent=parent) else: return _register_cascaded_service(url, type, name, username, password, wms=wms, owner=owner, parent=parent)
def main(): wms = WebMapService('http://maps.nzoss.org.nz/mapserv?template=openlayers&service=wms&request=getCapabilities', version='1.1.0') layer = 'default' crs = wms[layer].crsOptions print(crs) bbox = wms[layer].boundingBox print(bbox)