From 32d26a9bc20fcca48f59bd52e5e657b30191dc5b Mon Sep 17 00:00:00 2001 From: Michael Davie Date: Sun, 1 Nov 2026 10:53:09 -0500 Subject: [PATCH 1/4] WMS: add buildGetMapURL() and buildGetFeatureInfoURL() Return the URL that getmap()/getfeatureinfo() would request, without sending it, so callers can fetch with their own HTTP client (for example aiohttp). Together with the existing xml= constructor argument, this lets WMS be used without blocking I/O. The names follow WMTS's buildTileRequest() and buildTileResource(). The operation URL lookup and GetFeatureInfo parameter building move into private helpers shared by the request and URL methods; behaviour of getmap() and getfeatureinfo() is unchanged. --- docs/source/usage.rst | 15 + owslib/map/wms111.py | 125 ++++-- owslib/map/wms130.py | 139 +++++-- tests/resources/wms_geomet_radar_caps_130.xml | 378 ++++++++++++++++++ tests/test_wms_getmap.py | 89 ++++- 5 files changed, 693 insertions(+), 53 deletions(-) create mode 100644 tests/resources/wms_geomet_radar_caps_130.xml diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 83a168e3..eca0d070 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -73,6 +73,21 @@ Result: :height: 250px :alt: WMS GetMap generated by OWSLib +To fetch the image with another HTTP client (an asynchronous one, for example), build the +request URL without sending it. ``buildGetMapURL`` takes the same parameters as ``getmap``, and +``buildGetFeatureInfoURL`` does the same for ``getfeatureinfo``: + +.. code-block:: python + + >>> url = wms.buildGetMapURL(layers=['goes_west_ir'], + size=(300, 250), + bbox=(-126, 24, -66, 50), + srs='EPSG:4326', + format='image/png') + +If a capabilities document has already been fetched the same way, pass it to the constructor +with ``xml=`` and OWSLib will parse it instead of requesting it. + WFS --- diff --git a/owslib/map/wms111.py b/owslib/map/wms111.py index be91121d..7b115ce3 100644 --- a/owslib/map/wms111.py +++ b/owslib/map/wms111.py @@ -237,11 +237,7 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, out.close() """ - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods - if m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url + base_url = self._operation_url('GetMap', method) request = {'version': self.version, 'request': 'GetMap'} request = self.__build_getmap_request( @@ -271,6 +267,48 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, raise ServiceException(err_message) return u + def buildGetMapURL(self, layers=None, styles=None, srs=None, bbox=None, + format=None, size=None, time=None, transparent=False, + bgcolor='#FFFFFF', + exceptions='application/vnd.ogc.se_xml', + **kwargs + ): + """Return the URL of a GetMap request without sending it. + + Takes the same parameters as getmap() and returns the URL that + getmap(method='Get') would request. Useful for fetching the image + with another HTTP client, such as an asynchronous one. + """ + request = self.__build_getmap_request( + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + **kwargs) + + return bind_url(self._operation_url('GetMap', 'Get')) + urlencode(request) + + def __build_getfeatureinfo_request(self, query_layers=None, xy=None, info_format=None, + feature_count=20, **kwargs): + + # GetMap-Request + request = self.__build_getmap_request(**kwargs) + + # extend to GetFeatureInfo-Request + request['request'] = 'GetFeatureInfo' + request['query_layers'] = ','.join(query_layers or kwargs['layers']) + request['x'] = str(xy[0]) + request['y'] = str(xy[1]) + request['info_format'] = info_format + request['feature_count'] = str(feature_count) + return request + def getfeatureinfo(self, layers=None, styles=None, @@ -290,14 +328,9 @@ def getfeatureinfo(self, timeout=None, **kwargs ): - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetFeatureInfo').methods - if m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url + base_url = self._operation_url('GetFeatureInfo', method) - # GetMap-Request - request = self.__build_getmap_request( + request = self.__build_getfeatureinfo_request( layers=layers, styles=styles, srs=srs, @@ -308,22 +341,12 @@ def getfeatureinfo(self, transparent=transparent, bgcolor=bgcolor, exceptions=exceptions, + query_layers=query_layers, + xy=xy, + info_format=info_format, + feature_count=feature_count, **kwargs) - # extend to GetFeatureInfo-Request - request['request'] = 'GetFeatureInfo' - - if not query_layers: - __str_query_layers = ','.join(layers) - else: - __str_query_layers = ','.join(query_layers) - - request['query_layers'] = __str_query_layers - request['x'] = str(xy[0]) - request['y'] = str(xy[1]) - request['info_format'] = info_format - request['feature_count'] = str(feature_count) - data = urlencode(request) self.request = bind_url(base_url) + data @@ -338,6 +361,47 @@ def getfeatureinfo(self, raise ServiceException(err_message) return u + def buildGetFeatureInfoURL(self, + layers=None, + styles=None, + srs=None, + bbox=None, + format=None, + size=None, + time=None, + transparent=False, + bgcolor='#FFFFFF', + exceptions='application/vnd.ogc.se_xml', + query_layers=None, + xy=None, + info_format=None, + feature_count=20, + **kwargs + ): + """Return the URL of a GetFeatureInfo request without sending it. + + Takes the same parameters as getfeatureinfo() and returns the URL + that getfeatureinfo(method='Get') would request. + """ + request = self.__build_getfeatureinfo_request( + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + query_layers=query_layers, + xy=xy, + info_format=info_format, + feature_count=feature_count, + **kwargs) + + return bind_url(self._operation_url('GetFeatureInfo', 'Get')) + urlencode(request) + def getServiceXML(self): xml = None if self._capabilities is not None: @@ -351,6 +415,15 @@ def getOperationByName(self, name): return item raise KeyError("No operation named %s" % name) + def _operation_url(self, name, method): + """Return the URL advertised for an operation and HTTP DCP method, + or the service URL if none is advertised.""" + try: + return next((m.get('url') for m in self.getOperationByName(name).methods + if m.get('type').lower() == method.lower())) + except StopIteration: + return self.url + class ServiceIdentification(object): ''' Implements IServiceIdentificationMetadata ''' diff --git a/owslib/map/wms130.py b/owslib/map/wms130.py index 914af679..e1e38eea 100644 --- a/owslib/map/wms130.py +++ b/owslib/map/wms130.py @@ -152,6 +152,15 @@ def getOperationByName(self, name): return item raise KeyError("No operation named %s" % name) + def _operation_url(self, name, method): + """Return the URL advertised for an operation and HTTP DCP method, + or the service URL if none is advertised.""" + try: + return next((m.get('url') for m in self.getOperationByName(name).methods + if m.get('type').lower() == method.lower())) + except StopIteration: + return self.url + def __build_getmap_request(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, dimensions={}, elevation=None, transparent=False, @@ -282,12 +291,7 @@ def getmap(self, layers=None, """ - try: - base_url = next((m.get('url') for m in - self.getOperationByName('GetMap').methods if - m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url + base_url = self._operation_url('GetMap', method) request = self.__build_getmap_request( layers=layers, @@ -323,7 +327,7 @@ def getmap(self, layers=None, raise ServiceException(err_message) return u - def getfeatureinfo(self, layers=None, + def buildGetMapURL(self, layers=None, styles=None, srs=None, bbox=None, @@ -335,21 +339,15 @@ def getfeatureinfo(self, layers=None, transparent=False, bgcolor='#FFFFFF', exceptions='XML', - query_layers=None, - xy=None, - info_format=None, - feature_count=20, - method='Get', - timeout=None, **kwargs ): - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetFeatureInfo').methods - if m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url + """Return the URL of a GetMap request without sending it. + + Takes the same parameters as getmap() and returns the URL that + getmap(method='Get') would request. Useful for fetching the image + with another HTTP client, such as an asynchronous one. + """ - # GetMap-Request request = self.__build_getmap_request( layers=layers, styles=styles, @@ -365,19 +363,63 @@ def getfeatureinfo(self, layers=None, exceptions=exceptions, **kwargs) - # extend to GetFeatureInfo-Request - request['request'] = 'GetFeatureInfo' + return bind_url(self._operation_url('GetMap', 'Get')) + urlencode(request) - if not query_layers: - __str_query_layers = ','.join(layers) - else: - __str_query_layers = ','.join(query_layers) + def __build_getfeatureinfo_request(self, query_layers=None, xy=None, info_format=None, + feature_count=20, **kwargs): - request['query_layers'] = __str_query_layers + # GetMap-Request + request = self.__build_getmap_request(**kwargs) + + # extend to GetFeatureInfo-Request + request['request'] = 'GetFeatureInfo' + request['query_layers'] = ','.join(query_layers or kwargs['layers']) request['i'] = str(xy[0]) request['j'] = str(xy[1]) request['info_format'] = info_format request['feature_count'] = str(feature_count) + return request + + def getfeatureinfo(self, layers=None, + styles=None, + srs=None, + bbox=None, + format=None, + size=None, + time=None, + elevation=None, + dimensions={}, + transparent=False, + bgcolor='#FFFFFF', + exceptions='XML', + query_layers=None, + xy=None, + info_format=None, + feature_count=20, + method='Get', + timeout=None, + **kwargs + ): + base_url = self._operation_url('GetFeatureInfo', method) + + request = self.__build_getfeatureinfo_request( + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + dimensions=dimensions, + elevation=elevation, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + query_layers=query_layers, + xy=xy, + info_format=info_format, + feature_count=feature_count, + **kwargs) data = urlencode(request) @@ -393,6 +435,51 @@ def getfeatureinfo(self, layers=None, raise ServiceException(err_message) return u + def buildGetFeatureInfoURL(self, layers=None, + styles=None, + srs=None, + bbox=None, + format=None, + size=None, + time=None, + elevation=None, + dimensions={}, + transparent=False, + bgcolor='#FFFFFF', + exceptions='XML', + query_layers=None, + xy=None, + info_format=None, + feature_count=20, + **kwargs + ): + """Return the URL of a GetFeatureInfo request without sending it. + + Takes the same parameters as getfeatureinfo() and returns the URL + that getfeatureinfo(method='Get') would request. + """ + + request = self.__build_getfeatureinfo_request( + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + dimensions=dimensions, + elevation=elevation, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + query_layers=query_layers, + xy=xy, + info_format=info_format, + feature_count=feature_count, + **kwargs) + + return bind_url(self._operation_url('GetFeatureInfo', 'Get')) + urlencode(request) + class ServiceIdentification(object): def __init__(self, infoset, version): diff --git a/tests/resources/wms_geomet_radar_caps_130.xml b/tests/resources/wms_geomet_radar_caps_130.xml new file mode 100644 index 00000000..05d00ac6 --- /dev/null +++ b/tests/resources/wms_geomet_radar_caps_130.xml @@ -0,0 +1,378 @@ + + + + WMS + MSC GeoMet — GeoMet-Weather 2.40.4 + GeoMet-Weather provides public access to the Meteorological Service of Canada (MSC) and Environment and Climate Change Canada (ECCC) data via interoperable web services and application programming interfaces (API). Through open standards, users can freely and quickly access thousands of real-time and archived weather, climate and water datasets and products and integrate them in their domain-specific applications and decision support systems. Users can build mobile apps, create interactive web maps, and display and animate MSC data in desktop software. MSC GeoMet also enables on demand raw data clipping and reprojection, on demand format conversion and custom visualization. + + Weather + Meteorology + Climate + Forecasting + Floods + Weather alerts + Storms + Wind + Temperature + Precipitations + Snow + Ice + + + + + National Inquiry Response Team + Government of Canada, Environment and Climate Change Canada, Meteorological Service of Canada + + Service Channel + + postal +
77 Westmorland Street, Suite 260
+ Fredericton + New Brunswick + E3B 6Z3 + Canada +
+ None + +01-506-451-6010 + ecweather-meteo@ec.gc.ca +
+ None + None + 16384 + 16384 +
+ + + + + text/xml + + + + + + + + + image/png + image/jpeg + image/webp + + + + + + + + + text/plain + application/json + application/vnd.ogc.gml + + + + + + + + + text/xml + + + + + + + + + image/png + image/jpeg + image/png; mode=8bit + image/vnd.jpeg-png + image/vnd.jpeg-png8 + + + + + + + + + text/xml + + + + + + + + + + XML + INIMAGE + BLANK + + + + MSC GeoMet — GeoMet-Weather 2.40.4 + GeoMet-Weather provides public access to the Meteorological Service of Canada (MSC) and Environment and Climate Change Canada (ECCC) data via interoperable web services and application programming interfaces (API). Through open standards, users can freely and quickly access thousands of real-time and archived weather, climate and water datasets and products and integrate them in their domain-specific applications and decision support systems. Users can build mobile apps, create interactive web maps, and display and animate MSC data in desktop software. MSC GeoMet also enables on demand raw data clipping and reprojection, on demand format conversion and custom visualization. + + Weather + Meteorology + Climate + Forecasting + Floods + Weather alerts + Storms + Wind + Temperature + Precipitations + Snow + Ice + + EPSG:4326 + EPSG:2294 + EPSG:2295 + EPSG:2950 + EPSG:3005 + EPSG:3408 + EPSG:3410 + EPSG:3571 + EPSG:3572 + EPSG:3573 + EPSG:3574 + EPSG:3575 + EPSG:3576 + EPSG:3776 + EPSG:3857 + EPSG:3978 + EPSG:3995 + EPSG:4267 + EPSG:4269 + EPSG:26707 + EPSG:26708 + EPSG:26709 + EPSG:26710 + EPSG:26711 + EPSG:26712 + EPSG:26713 + EPSG:26714 + EPSG:26715 + EPSG:26716 + EPSG:26717 + EPSG:26718 + EPSG:26719 + EPSG:26720 + EPSG:26721 + EPSG:26722 + EPSG:26907 + EPSG:26908 + EPSG:26909 + EPSG:26910 + EPSG:26911 + EPSG:26912 + EPSG:26913 + EPSG:26914 + EPSG:26915 + EPSG:26916 + EPSG:26917 + EPSG:26918 + EPSG:26919 + EPSG:26920 + EPSG:26921 + EPSG:26922 + EPSG:32187 + EPSG:32188 + EPSG:32198 + EPSG:32661 + EPSG:42101 + EPSG:42102 + EPSG:42304 + EPSG:102100 + EPSG:102185 + EPSG:900913 + AUTO2:42003 + + -180.000000 + 180.000000 + -90.000000 + 90.000000 + + + + Government of Canada, Environment and Climate Change Canada, Meteorological Service of Canada + + + image/jpeg + + + + + Weather Radar + Weather Radar + + North American radar composite [1 km] + North American radar composite [1 km] + + RADAR_1KM_RRAI + Radar precipitation rate for rain [mm/h] + This mosaic is calculated over the North American domain with a horizontal spatial resolution of 1 km. This mosaic therefore includes all the Canadian and American radars available in the network and which can reach a maximum of 180 contributing radars. To better represent precipitation over the different seasons, this mosaic renders in mm/h to represent rain and in cm/h to represent snow. For the two precipitation types (rain and snow), we use two different mathematical relationships to convert the reflectivity by rainfall rates (mm/h rain cm/h for snow). This mosaic is based on the DPQPE (Dual-Pol Quantitative Precipitation Estimation) product for S-Band radars. For the US Nexrad radars, ECCC uses the most similar product from the US Meteorological Service (NOAA). This product displays radar reflectivity converted into precipitation rates, using the same formulas as the Canadian radars. + + Atmospheric conditions + Meteorology + Weather + Radar + Remote sensing + Weather + + + -170.320000 + -50.000000 + 16.930000 + 67.190000 + + 2026-11-01T12:42:00Z/2026-11-01T15:42:00Z/PT6M + + + + urn:x-msc-smc:md:weather-meteo::radar.composite + + text/xml + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/tests/test_wms_getmap.py b/tests/test_wms_getmap.py index dad1d3cd..c7e5ce88 100644 --- a/tests/test_wms_getmap.py +++ b/tests/test_wms_getmap.py @@ -1,7 +1,8 @@ from unittest import mock +from urllib.parse import parse_qs, urlsplit import pytest -from tests.utils import service_ok +from tests.utils import resource_file, service_ok from owslib.wms import WebMapService from owslib.map.wms130 import WebMapService_1_3_0 @@ -11,6 +12,7 @@ SERVICE_URL = 'http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r-t.cgi' NCWMS2_URL = "http://wms.stccmop.org:8080/ncWMS2/wms" +GEOMET_URL = 'https://geo.weather.gc.ca/geomet' @pytest.fixture @@ -18,6 +20,91 @@ def wms(): return WebMapService_1_3_0(SERVICE_URL, version='1.3.0') +def wms_from_resource(version): + """A WMS built from a stored capabilities document, without network access: + MSC GeoMet for 1.3.0, IEM Mesonet for 1.1.1.""" + if version == '1.3.0': + url, filename = GEOMET_URL, 'wms_geomet_radar_caps_130.xml' + else: + url, filename = SERVICE_URL, 'wms_mesonet-caps.xml' + with open(resource_file(filename), 'rb') as f: + return WebMapService(url, version=version, xml=f.read()) + + +GETMAP_PARAMS = { + '1.3.0': dict(layers=['RADAR_1KM_RRAI'], styles=['Radar-Rain_14colors'], srs='EPSG:4326', + bbox=(-80.0, 43.0, -79.0, 44.0), size=(256, 256), format='image/png', + transparent=True, time='2026-11-01T15:42:00Z'), + '1.1.1': dict(layers=['nexrad_base_reflect'], styles=['default'], srs='EPSG:4326', + bbox=(-126, 24, -66, 50), size=(250, 250), format='image/jpeg', + transparent=True), +} + + +def image_response(): + response = mock.Mock() + response.info.return_value = {'Content-Type': 'image/png'} + return response + + +@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) +def test_build_getmap_url_is_the_url_getmap_requests(version): + """buildGetMapURL() returns exactly the URL getmap() requests, so a caller + can fetch the image with its own HTTP client (e.g. an asyncio one).""" + wms = wms_from_resource(version) + params = GETMAP_PARAMS[version] + module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' + + with mock.patch(f'{module}.openURL', return_value=image_response()): + wms.getmap(**params) + + assert wms.buildGetMapURL(**params) == wms.request + + +@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) +def test_build_getmap_url_makes_no_request(version): + """buildGetMapURL() only builds the URL; it never touches the network.""" + wms = wms_from_resource(version) + module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' + + with mock.patch(f'{module}.openURL', side_effect=AssertionError('no request expected')): + wms.buildGetMapURL(**GETMAP_PARAMS[version]) + + +def test_build_getmap_url_130_geomet(): + """A GeoMet radar frame: the advertised GetMap URL, the time dimension, + and the bbox swapped to lat/lon for EPSG:4326 under WMS 1.3.0.""" + url = wms_from_resource('1.3.0').buildGetMapURL(**GETMAP_PARAMS['1.3.0']) + + parts = urlsplit(url) + assert f'{parts.scheme}://{parts.netloc}{parts.path}' == GEOMET_URL + query = {k: v[0] for k, v in parse_qs(parts.query, keep_blank_values=True).items()} + assert query['request'] == 'GetMap' + assert query['layers'] == 'RADAR_1KM_RRAI' + assert query['crs'] == 'EPSG:4326' + assert query['bbox'] == '43.0,-80.0,44.0,-79.0' + assert query['time'] == '2026-11-01T15:42:00Z' + + +@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) +def test_build_getfeatureinfo_url_is_the_url_getfeatureinfo_requests(version): + """buildGetFeatureInfoURL() returns exactly the URL getfeatureinfo() requests.""" + wms = wms_from_resource(version) + params = dict(GETMAP_PARAMS[version], xy=(128, 128), info_format='text/plain') + module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' + + with mock.patch(f'{module}.openURL', return_value=image_response()): + wms.getfeatureinfo(**params) + + url = wms.buildGetFeatureInfoURL(**params) + assert url == wms.request + query = parse_qs(urlsplit(url).query) + assert query['request'] == ['GetFeatureInfo'] + assert query['query_layers'] == params['layers'] + pixel = ('i', 'j') if version == '1.3.0' else ('x', 'y') + assert [query[k] for k in pixel] == [['128'], ['128']] + + @pytest.mark.parametrize("version", ["1.3.0", "1.1.1"]) def test_build_getmap_request_bbox_precision(version): bbox = (-126.123456789, 24.123456789, -66.123456789, 50.123456789) From 817be9b4fc81dc07a5038af3e9c1ec71424e8b31 Mon Sep 17 00:00:00 2001 From: Michael Davie Date: Sun, 1 Nov 2026 15:57:28 -0500 Subject: [PATCH 2/4] Trim to a single buildGetMapURL() per WMS version Address review: drop buildGetFeatureInfoURL() and the refactor of getmap()/getfeatureinfo(), pass getmap()'s parameters straight through to the existing private builder, and test against the existing Mesonet capabilities documents instead of adding a new fixture. --- docs/source/usage.rst | 16 +- owslib/map/wms111.py | 133 ++---- owslib/map/wms130.py | 149 ++----- tests/resources/wms_geomet_radar_caps_130.xml | 378 ------------------ tests/test_wms_getmap.py | 103 +---- 5 files changed, 93 insertions(+), 686 deletions(-) delete mode 100644 tests/resources/wms_geomet_radar_caps_130.xml diff --git a/docs/source/usage.rst b/docs/source/usage.rst index eca0d070..892bf445 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -73,20 +73,8 @@ Result: :height: 250px :alt: WMS GetMap generated by OWSLib -To fetch the image with another HTTP client (an asynchronous one, for example), build the -request URL without sending it. ``buildGetMapURL`` takes the same parameters as ``getmap``, and -``buildGetFeatureInfoURL`` does the same for ``getfeatureinfo``: - -.. code-block:: python - - >>> url = wms.buildGetMapURL(layers=['goes_west_ir'], - size=(300, 250), - bbox=(-126, 24, -66, 50), - srs='EPSG:4326', - format='image/png') - -If a capabilities document has already been fetched the same way, pass it to the constructor -with ``xml=`` and OWSLib will parse it instead of requesting it. +To fetch the image with another HTTP client, ``buildGetMapURL`` takes the same parameters +and returns the URL without sending a request. WFS diff --git a/owslib/map/wms111.py b/owslib/map/wms111.py index 7b115ce3..eb09fbbb 100644 --- a/owslib/map/wms111.py +++ b/owslib/map/wms111.py @@ -237,7 +237,11 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, out.close() """ - base_url = self._operation_url('GetMap', method) + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods + if m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url request = {'version': self.version, 'request': 'GetMap'} request = self.__build_getmap_request( @@ -267,47 +271,19 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, raise ServiceException(err_message) return u - def buildGetMapURL(self, layers=None, styles=None, srs=None, bbox=None, - format=None, size=None, time=None, transparent=False, - bgcolor='#FFFFFF', - exceptions='application/vnd.ogc.se_xml', - **kwargs - ): - """Return the URL of a GetMap request without sending it. + def buildGetMapURL(self, **kwargs): + """Return the URL that getmap(method='Get') would request, without sending it. - Takes the same parameters as getmap() and returns the URL that - getmap(method='Get') would request. Useful for fetching the image - with another HTTP client, such as an asynchronous one. + Takes the same parameters as getmap(), except method and timeout. """ - request = self.__build_getmap_request( - layers=layers, - styles=styles, - srs=srs, - bbox=bbox, - format=format, - size=size, - time=time, - transparent=transparent, - bgcolor=bgcolor, - exceptions=exceptions, - **kwargs) - - return bind_url(self._operation_url('GetMap', 'Get')) + urlencode(request) - - def __build_getfeatureinfo_request(self, query_layers=None, xy=None, info_format=None, - feature_count=20, **kwargs): - - # GetMap-Request - request = self.__build_getmap_request(**kwargs) - - # extend to GetFeatureInfo-Request - request['request'] = 'GetFeatureInfo' - request['query_layers'] = ','.join(query_layers or kwargs['layers']) - request['x'] = str(xy[0]) - request['y'] = str(xy[1]) - request['info_format'] = info_format - request['feature_count'] = str(feature_count) - return request + kwargs.setdefault('bgcolor', '#FFFFFF') + kwargs.setdefault('exceptions', 'application/vnd.ogc.se_xml') + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods + if m.get('type').lower() == 'get')) + except StopIteration: + base_url = self.url + return bind_url(base_url) + urlencode(self.__build_getmap_request(**kwargs)) def getfeatureinfo(self, layers=None, @@ -328,9 +304,14 @@ def getfeatureinfo(self, timeout=None, **kwargs ): - base_url = self._operation_url('GetFeatureInfo', method) + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetFeatureInfo').methods + if m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url - request = self.__build_getfeatureinfo_request( + # GetMap-Request + request = self.__build_getmap_request( layers=layers, styles=styles, srs=srs, @@ -341,12 +322,22 @@ def getfeatureinfo(self, transparent=transparent, bgcolor=bgcolor, exceptions=exceptions, - query_layers=query_layers, - xy=xy, - info_format=info_format, - feature_count=feature_count, **kwargs) + # extend to GetFeatureInfo-Request + request['request'] = 'GetFeatureInfo' + + if not query_layers: + __str_query_layers = ','.join(layers) + else: + __str_query_layers = ','.join(query_layers) + + request['query_layers'] = __str_query_layers + request['x'] = str(xy[0]) + request['y'] = str(xy[1]) + request['info_format'] = info_format + request['feature_count'] = str(feature_count) + data = urlencode(request) self.request = bind_url(base_url) + data @@ -361,47 +352,6 @@ def getfeatureinfo(self, raise ServiceException(err_message) return u - def buildGetFeatureInfoURL(self, - layers=None, - styles=None, - srs=None, - bbox=None, - format=None, - size=None, - time=None, - transparent=False, - bgcolor='#FFFFFF', - exceptions='application/vnd.ogc.se_xml', - query_layers=None, - xy=None, - info_format=None, - feature_count=20, - **kwargs - ): - """Return the URL of a GetFeatureInfo request without sending it. - - Takes the same parameters as getfeatureinfo() and returns the URL - that getfeatureinfo(method='Get') would request. - """ - request = self.__build_getfeatureinfo_request( - layers=layers, - styles=styles, - srs=srs, - bbox=bbox, - format=format, - size=size, - time=time, - transparent=transparent, - bgcolor=bgcolor, - exceptions=exceptions, - query_layers=query_layers, - xy=xy, - info_format=info_format, - feature_count=feature_count, - **kwargs) - - return bind_url(self._operation_url('GetFeatureInfo', 'Get')) + urlencode(request) - def getServiceXML(self): xml = None if self._capabilities is not None: @@ -415,15 +365,6 @@ def getOperationByName(self, name): return item raise KeyError("No operation named %s" % name) - def _operation_url(self, name, method): - """Return the URL advertised for an operation and HTTP DCP method, - or the service URL if none is advertised.""" - try: - return next((m.get('url') for m in self.getOperationByName(name).methods - if m.get('type').lower() == method.lower())) - except StopIteration: - return self.url - class ServiceIdentification(object): ''' Implements IServiceIdentificationMetadata ''' diff --git a/owslib/map/wms130.py b/owslib/map/wms130.py index e1e38eea..3ba4508b 100644 --- a/owslib/map/wms130.py +++ b/owslib/map/wms130.py @@ -152,15 +152,6 @@ def getOperationByName(self, name): return item raise KeyError("No operation named %s" % name) - def _operation_url(self, name, method): - """Return the URL advertised for an operation and HTTP DCP method, - or the service URL if none is advertised.""" - try: - return next((m.get('url') for m in self.getOperationByName(name).methods - if m.get('type').lower() == method.lower())) - except StopIteration: - return self.url - def __build_getmap_request(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, dimensions={}, elevation=None, transparent=False, @@ -291,7 +282,12 @@ def getmap(self, layers=None, """ - base_url = self._operation_url('GetMap', method) + try: + base_url = next((m.get('url') for m in + self.getOperationByName('GetMap').methods if + m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url request = self.__build_getmap_request( layers=layers, @@ -327,58 +323,19 @@ def getmap(self, layers=None, raise ServiceException(err_message) return u - def buildGetMapURL(self, layers=None, - styles=None, - srs=None, - bbox=None, - format=None, - size=None, - time=None, - elevation=None, - dimensions={}, - transparent=False, - bgcolor='#FFFFFF', - exceptions='XML', - **kwargs - ): - """Return the URL of a GetMap request without sending it. + def buildGetMapURL(self, **kwargs): + """Return the URL that getmap(method='Get') would request, without sending it. - Takes the same parameters as getmap() and returns the URL that - getmap(method='Get') would request. Useful for fetching the image - with another HTTP client, such as an asynchronous one. + Takes the same parameters as getmap(), except method and timeout. """ - - request = self.__build_getmap_request( - layers=layers, - styles=styles, - srs=srs, - bbox=bbox, - dimensions=dimensions, - elevation=elevation, - format=format, - size=size, - time=time, - transparent=transparent, - bgcolor=bgcolor, - exceptions=exceptions, - **kwargs) - - return bind_url(self._operation_url('GetMap', 'Get')) + urlencode(request) - - def __build_getfeatureinfo_request(self, query_layers=None, xy=None, info_format=None, - feature_count=20, **kwargs): - - # GetMap-Request - request = self.__build_getmap_request(**kwargs) - - # extend to GetFeatureInfo-Request - request['request'] = 'GetFeatureInfo' - request['query_layers'] = ','.join(query_layers or kwargs['layers']) - request['i'] = str(xy[0]) - request['j'] = str(xy[1]) - request['info_format'] = info_format - request['feature_count'] = str(feature_count) - return request + kwargs.setdefault('bgcolor', '#FFFFFF') + kwargs.setdefault('exceptions', 'XML') + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods + if m.get('type').lower() == 'get')) + except StopIteration: + base_url = self.url + return bind_url(base_url) + urlencode(self.__build_getmap_request(**kwargs)) def getfeatureinfo(self, layers=None, styles=None, @@ -400,9 +357,14 @@ def getfeatureinfo(self, layers=None, timeout=None, **kwargs ): - base_url = self._operation_url('GetFeatureInfo', method) + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetFeatureInfo').methods + if m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url - request = self.__build_getfeatureinfo_request( + # GetMap-Request + request = self.__build_getmap_request( layers=layers, styles=styles, srs=srs, @@ -415,12 +377,22 @@ def getfeatureinfo(self, layers=None, transparent=transparent, bgcolor=bgcolor, exceptions=exceptions, - query_layers=query_layers, - xy=xy, - info_format=info_format, - feature_count=feature_count, **kwargs) + # extend to GetFeatureInfo-Request + request['request'] = 'GetFeatureInfo' + + if not query_layers: + __str_query_layers = ','.join(layers) + else: + __str_query_layers = ','.join(query_layers) + + request['query_layers'] = __str_query_layers + request['i'] = str(xy[0]) + request['j'] = str(xy[1]) + request['info_format'] = info_format + request['feature_count'] = str(feature_count) + data = urlencode(request) self.request = bind_url(base_url) + data @@ -435,51 +407,6 @@ def getfeatureinfo(self, layers=None, raise ServiceException(err_message) return u - def buildGetFeatureInfoURL(self, layers=None, - styles=None, - srs=None, - bbox=None, - format=None, - size=None, - time=None, - elevation=None, - dimensions={}, - transparent=False, - bgcolor='#FFFFFF', - exceptions='XML', - query_layers=None, - xy=None, - info_format=None, - feature_count=20, - **kwargs - ): - """Return the URL of a GetFeatureInfo request without sending it. - - Takes the same parameters as getfeatureinfo() and returns the URL - that getfeatureinfo(method='Get') would request. - """ - - request = self.__build_getfeatureinfo_request( - layers=layers, - styles=styles, - srs=srs, - bbox=bbox, - dimensions=dimensions, - elevation=elevation, - format=format, - size=size, - time=time, - transparent=transparent, - bgcolor=bgcolor, - exceptions=exceptions, - query_layers=query_layers, - xy=xy, - info_format=info_format, - feature_count=feature_count, - **kwargs) - - return bind_url(self._operation_url('GetFeatureInfo', 'Get')) + urlencode(request) - class ServiceIdentification(object): def __init__(self, infoset, version): diff --git a/tests/resources/wms_geomet_radar_caps_130.xml b/tests/resources/wms_geomet_radar_caps_130.xml deleted file mode 100644 index 05d00ac6..00000000 --- a/tests/resources/wms_geomet_radar_caps_130.xml +++ /dev/null @@ -1,378 +0,0 @@ - - - - WMS - MSC GeoMet — GeoMet-Weather 2.40.4 - GeoMet-Weather provides public access to the Meteorological Service of Canada (MSC) and Environment and Climate Change Canada (ECCC) data via interoperable web services and application programming interfaces (API). Through open standards, users can freely and quickly access thousands of real-time and archived weather, climate and water datasets and products and integrate them in their domain-specific applications and decision support systems. Users can build mobile apps, create interactive web maps, and display and animate MSC data in desktop software. MSC GeoMet also enables on demand raw data clipping and reprojection, on demand format conversion and custom visualization. - - Weather - Meteorology - Climate - Forecasting - Floods - Weather alerts - Storms - Wind - Temperature - Precipitations - Snow - Ice - - - - - National Inquiry Response Team - Government of Canada, Environment and Climate Change Canada, Meteorological Service of Canada - - Service Channel - - postal -
77 Westmorland Street, Suite 260
- Fredericton - New Brunswick - E3B 6Z3 - Canada -
- None - +01-506-451-6010 - ecweather-meteo@ec.gc.ca -
- None - None - 16384 - 16384 -
- - - - - text/xml - - - - - - - - - image/png - image/jpeg - image/webp - - - - - - - - - text/plain - application/json - application/vnd.ogc.gml - - - - - - - - - text/xml - - - - - - - - - image/png - image/jpeg - image/png; mode=8bit - image/vnd.jpeg-png - image/vnd.jpeg-png8 - - - - - - - - - text/xml - - - - - - - - - - XML - INIMAGE - BLANK - - - - MSC GeoMet — GeoMet-Weather 2.40.4 - GeoMet-Weather provides public access to the Meteorological Service of Canada (MSC) and Environment and Climate Change Canada (ECCC) data via interoperable web services and application programming interfaces (API). Through open standards, users can freely and quickly access thousands of real-time and archived weather, climate and water datasets and products and integrate them in their domain-specific applications and decision support systems. Users can build mobile apps, create interactive web maps, and display and animate MSC data in desktop software. MSC GeoMet also enables on demand raw data clipping and reprojection, on demand format conversion and custom visualization. - - Weather - Meteorology - Climate - Forecasting - Floods - Weather alerts - Storms - Wind - Temperature - Precipitations - Snow - Ice - - EPSG:4326 - EPSG:2294 - EPSG:2295 - EPSG:2950 - EPSG:3005 - EPSG:3408 - EPSG:3410 - EPSG:3571 - EPSG:3572 - EPSG:3573 - EPSG:3574 - EPSG:3575 - EPSG:3576 - EPSG:3776 - EPSG:3857 - EPSG:3978 - EPSG:3995 - EPSG:4267 - EPSG:4269 - EPSG:26707 - EPSG:26708 - EPSG:26709 - EPSG:26710 - EPSG:26711 - EPSG:26712 - EPSG:26713 - EPSG:26714 - EPSG:26715 - EPSG:26716 - EPSG:26717 - EPSG:26718 - EPSG:26719 - EPSG:26720 - EPSG:26721 - EPSG:26722 - EPSG:26907 - EPSG:26908 - EPSG:26909 - EPSG:26910 - EPSG:26911 - EPSG:26912 - EPSG:26913 - EPSG:26914 - EPSG:26915 - EPSG:26916 - EPSG:26917 - EPSG:26918 - EPSG:26919 - EPSG:26920 - EPSG:26921 - EPSG:26922 - EPSG:32187 - EPSG:32188 - EPSG:32198 - EPSG:32661 - EPSG:42101 - EPSG:42102 - EPSG:42304 - EPSG:102100 - EPSG:102185 - EPSG:900913 - AUTO2:42003 - - -180.000000 - 180.000000 - -90.000000 - 90.000000 - - - - Government of Canada, Environment and Climate Change Canada, Meteorological Service of Canada - - - image/jpeg - - - - - Weather Radar - Weather Radar - - North American radar composite [1 km] - North American radar composite [1 km] - - RADAR_1KM_RRAI - Radar precipitation rate for rain [mm/h] - This mosaic is calculated over the North American domain with a horizontal spatial resolution of 1 km. This mosaic therefore includes all the Canadian and American radars available in the network and which can reach a maximum of 180 contributing radars. To better represent precipitation over the different seasons, this mosaic renders in mm/h to represent rain and in cm/h to represent snow. For the two precipitation types (rain and snow), we use two different mathematical relationships to convert the reflectivity by rainfall rates (mm/h rain cm/h for snow). This mosaic is based on the DPQPE (Dual-Pol Quantitative Precipitation Estimation) product for S-Band radars. For the US Nexrad radars, ECCC uses the most similar product from the US Meteorological Service (NOAA). This product displays radar reflectivity converted into precipitation rates, using the same formulas as the Canadian radars. - - Atmospheric conditions - Meteorology - Weather - Radar - Remote sensing - Weather - - - -170.320000 - -50.000000 - 16.930000 - 67.190000 - - 2026-11-01T12:42:00Z/2026-11-01T15:42:00Z/PT6M - - - - urn:x-msc-smc:md:weather-meteo::radar.composite - - text/xml - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/tests/test_wms_getmap.py b/tests/test_wms_getmap.py index c7e5ce88..5b2a2638 100644 --- a/tests/test_wms_getmap.py +++ b/tests/test_wms_getmap.py @@ -1,5 +1,4 @@ from unittest import mock -from urllib.parse import parse_qs, urlsplit import pytest from tests.utils import resource_file, service_ok @@ -12,7 +11,6 @@ SERVICE_URL = 'http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r-t.cgi' NCWMS2_URL = "http://wms.stccmop.org:8080/ncWMS2/wms" -GEOMET_URL = 'https://geo.weather.gc.ca/geomet' @pytest.fixture @@ -20,91 +18,6 @@ def wms(): return WebMapService_1_3_0(SERVICE_URL, version='1.3.0') -def wms_from_resource(version): - """A WMS built from a stored capabilities document, without network access: - MSC GeoMet for 1.3.0, IEM Mesonet for 1.1.1.""" - if version == '1.3.0': - url, filename = GEOMET_URL, 'wms_geomet_radar_caps_130.xml' - else: - url, filename = SERVICE_URL, 'wms_mesonet-caps.xml' - with open(resource_file(filename), 'rb') as f: - return WebMapService(url, version=version, xml=f.read()) - - -GETMAP_PARAMS = { - '1.3.0': dict(layers=['RADAR_1KM_RRAI'], styles=['Radar-Rain_14colors'], srs='EPSG:4326', - bbox=(-80.0, 43.0, -79.0, 44.0), size=(256, 256), format='image/png', - transparent=True, time='2026-11-01T15:42:00Z'), - '1.1.1': dict(layers=['nexrad_base_reflect'], styles=['default'], srs='EPSG:4326', - bbox=(-126, 24, -66, 50), size=(250, 250), format='image/jpeg', - transparent=True), -} - - -def image_response(): - response = mock.Mock() - response.info.return_value = {'Content-Type': 'image/png'} - return response - - -@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) -def test_build_getmap_url_is_the_url_getmap_requests(version): - """buildGetMapURL() returns exactly the URL getmap() requests, so a caller - can fetch the image with its own HTTP client (e.g. an asyncio one).""" - wms = wms_from_resource(version) - params = GETMAP_PARAMS[version] - module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' - - with mock.patch(f'{module}.openURL', return_value=image_response()): - wms.getmap(**params) - - assert wms.buildGetMapURL(**params) == wms.request - - -@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) -def test_build_getmap_url_makes_no_request(version): - """buildGetMapURL() only builds the URL; it never touches the network.""" - wms = wms_from_resource(version) - module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' - - with mock.patch(f'{module}.openURL', side_effect=AssertionError('no request expected')): - wms.buildGetMapURL(**GETMAP_PARAMS[version]) - - -def test_build_getmap_url_130_geomet(): - """A GeoMet radar frame: the advertised GetMap URL, the time dimension, - and the bbox swapped to lat/lon for EPSG:4326 under WMS 1.3.0.""" - url = wms_from_resource('1.3.0').buildGetMapURL(**GETMAP_PARAMS['1.3.0']) - - parts = urlsplit(url) - assert f'{parts.scheme}://{parts.netloc}{parts.path}' == GEOMET_URL - query = {k: v[0] for k, v in parse_qs(parts.query, keep_blank_values=True).items()} - assert query['request'] == 'GetMap' - assert query['layers'] == 'RADAR_1KM_RRAI' - assert query['crs'] == 'EPSG:4326' - assert query['bbox'] == '43.0,-80.0,44.0,-79.0' - assert query['time'] == '2026-11-01T15:42:00Z' - - -@pytest.mark.parametrize('version', ['1.3.0', '1.1.1']) -def test_build_getfeatureinfo_url_is_the_url_getfeatureinfo_requests(version): - """buildGetFeatureInfoURL() returns exactly the URL getfeatureinfo() requests.""" - wms = wms_from_resource(version) - params = dict(GETMAP_PARAMS[version], xy=(128, 128), info_format='text/plain') - module = 'owslib.map.wms130' if version == '1.3.0' else 'owslib.map.wms111' - - with mock.patch(f'{module}.openURL', return_value=image_response()): - wms.getfeatureinfo(**params) - - url = wms.buildGetFeatureInfoURL(**params) - assert url == wms.request - query = parse_qs(urlsplit(url).query) - assert query['request'] == ['GetFeatureInfo'] - assert query['query_layers'] == params['layers'] - pixel = ('i', 'j') if version == '1.3.0' else ('x', 'y') - assert [query[k] for k in pixel] == [['128'], ['128']] - - @pytest.mark.parametrize("version", ["1.3.0", "1.1.1"]) def test_build_getmap_request_bbox_precision(version): bbox = (-126.123456789, 24.123456789, -66.123456789, 50.123456789) @@ -125,6 +38,22 @@ def test_build_getmap_request_bbox_precision(version): assert request['bbox'] == ','.join(map(str, bbox_yx)) +@pytest.mark.parametrize("version, caps", [("1.3.0", "wms_mesonet-caps-130.xml"), ("1.1.1", "wms_mesonet-caps.xml")]) +def test_build_getmap_url(version, caps): + """buildGetMapURL returns the URL getmap would request""" + with open(resource_file(caps), 'rb') as f: + wms = WebMapService(SERVICE_URL, version=version, xml=f.read()) + params = dict(layers=['nexrad_base_reflect'], srs='EPSG:4326', bbox=(-126, 24, -66, 50), + size=(250, 250), format='image/png', time='2006-06-23T03:10:00Z') + + response = mock.Mock() + response.info.return_value = {'Content-Type': 'image/png'} + with mock.patch(f"owslib.map.wms{version.replace('.', '')}.openURL", return_value=response): + wms.getmap(**params) + + assert wms.buildGetMapURL(**params) == wms.request + + @pytest.mark.online @pytest.mark.skipif(not service_ok(SERVICE_URL), reason="WMS service is unreachable") From 6873189d6e0c2acc53c7d7b518e6f5b8bf23864f Mon Sep 17 00:00:00 2001 From: Michael Davie Date: Mon, 2 Nov 2026 21:59:24 -0500 Subject: [PATCH 3/4] Share GetMap URL building with getmap(), list parameters explicitly, add GeoMet example Moves the base URL lookup and request encoding into a private __build_getmap_url() used by both getmap() and buildGetMapURL(), gives buildGetMapURL() the same explicit parameters as getmap(), and adds an aiohttp example against MSC GeoMet to usage.rst. --- docs/source/usage.rst | 19 ++++++++++++-- owslib/map/wms111.py | 49 +++++++++++++++++++++-------------- owslib/map/wms130.py | 60 +++++++++++++++++++++++++++++-------------- 3 files changed, 88 insertions(+), 40 deletions(-) diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 892bf445..d64f187c 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -73,8 +73,23 @@ Result: :height: 250px :alt: WMS GetMap generated by OWSLib -To fetch the image with another HTTP client, ``buildGetMapURL`` takes the same parameters -and returns the URL without sending a request. +``getmap`` sends a blocking request. To fetch the image with another HTTP client, such as ``aiohttp`` in an +``asyncio`` application, ``buildGetMapURL`` takes the same parameters and returns the URL without sending a request. +For example, the latest radar frame from MSC GeoMet: + +.. code-block:: python + + >>> import aiohttp + >>> wms = WebMapService('https://geo.weather.gc.ca/geomet?layer=RADAR_1KM_RRAI', version='1.3.0') + >>> url = wms.buildGetMapURL(layers=['RADAR_1KM_RRAI'], + srs='CRS:84', + bbox=(-95, 41, -73, 57), + size=(800, 600), + format='image/png', + time=wms['RADAR_1KM_RRAI'].defaulttimeposition) + >>> async with aiohttp.ClientSession() as session: + ... async with session.get(url) as response: + ... png = await response.read() WFS diff --git a/owslib/map/wms111.py b/owslib/map/wms111.py index eb09fbbb..33483ca1 100644 --- a/owslib/map/wms111.py +++ b/owslib/map/wms111.py @@ -188,6 +188,14 @@ def __build_getmap_request(self, layers=None, styles=None, srs=None, bbox=None, request[kw] = kwargs[kw] return request + def __build_getmap_url(self, method, **kwargs): + try: + base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods + if m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url + return base_url, urlencode(self.__build_getmap_request(**kwargs)) + def getmap(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, transparent=False, bgcolor='#FFFFFF', @@ -237,14 +245,8 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, out.close() """ - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods - if m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url - request = {'version': self.version, 'request': 'GetMap'} - - request = self.__build_getmap_request( + base_url, data = self.__build_getmap_url( + method, layers=layers, styles=styles, srs=srs, @@ -257,8 +259,6 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, exceptions=exceptions, **kwargs) - data = urlencode(request) - self.request = bind_url(base_url) + data u = openURL(base_url, data, method, timeout=timeout or self.timeout, auth=self.auth, headers=self.headers) @@ -271,19 +271,30 @@ def getmap(self, layers=None, styles=None, srs=None, bbox=None, raise ServiceException(err_message) return u - def buildGetMapURL(self, **kwargs): + def buildGetMapURL(self, layers=None, styles=None, srs=None, bbox=None, + format=None, size=None, time=None, transparent=False, + bgcolor='#FFFFFF', + exceptions='application/vnd.ogc.se_xml', + **kwargs + ): """Return the URL that getmap(method='Get') would request, without sending it. Takes the same parameters as getmap(), except method and timeout. """ - kwargs.setdefault('bgcolor', '#FFFFFF') - kwargs.setdefault('exceptions', 'application/vnd.ogc.se_xml') - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods - if m.get('type').lower() == 'get')) - except StopIteration: - base_url = self.url - return bind_url(base_url) + urlencode(self.__build_getmap_request(**kwargs)) + base_url, data = self.__build_getmap_url( + 'Get', + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + **kwargs) + return bind_url(base_url) + data def getfeatureinfo(self, layers=None, diff --git a/owslib/map/wms130.py b/owslib/map/wms130.py index 3ba4508b..01792a4a 100644 --- a/owslib/map/wms130.py +++ b/owslib/map/wms130.py @@ -207,6 +207,15 @@ def __build_getmap_request(self, layers=None, styles=None, srs=None, bbox=None, request[kw] = kwargs[kw] return request + def __build_getmap_url(self, method, **kwargs): + try: + base_url = next((m.get('url') for m in + self.getOperationByName('GetMap').methods if + m.get('type').lower() == method.lower())) + except StopIteration: + base_url = self.url + return base_url, urlencode(self.__build_getmap_request(**kwargs)) + def getmap(self, layers=None, styles=None, srs=None, @@ -282,14 +291,8 @@ def getmap(self, layers=None, """ - try: - base_url = next((m.get('url') for m in - self.getOperationByName('GetMap').methods if - m.get('type').lower() == method.lower())) - except StopIteration: - base_url = self.url - - request = self.__build_getmap_request( + base_url, data = self.__build_getmap_url( + method, layers=layers, styles=styles, srs=srs, @@ -304,8 +307,6 @@ def getmap(self, layers=None, exceptions=exceptions, **kwargs) - data = urlencode(request) - self.request = bind_url(base_url) + data u = openURL(base_url, data, method, timeout=timeout or self.timeout, auth=self.auth, headers=self.headers) @@ -323,19 +324,40 @@ def getmap(self, layers=None, raise ServiceException(err_message) return u - def buildGetMapURL(self, **kwargs): + def buildGetMapURL(self, layers=None, + styles=None, + srs=None, + bbox=None, + format=None, + size=None, + time=None, + elevation=None, + dimensions={}, + transparent=False, + bgcolor='#FFFFFF', + exceptions='XML', + **kwargs + ): """Return the URL that getmap(method='Get') would request, without sending it. Takes the same parameters as getmap(), except method and timeout. """ - kwargs.setdefault('bgcolor', '#FFFFFF') - kwargs.setdefault('exceptions', 'XML') - try: - base_url = next((m.get('url') for m in self.getOperationByName('GetMap').methods - if m.get('type').lower() == 'get')) - except StopIteration: - base_url = self.url - return bind_url(base_url) + urlencode(self.__build_getmap_request(**kwargs)) + base_url, data = self.__build_getmap_url( + 'Get', + layers=layers, + styles=styles, + srs=srs, + bbox=bbox, + dimensions=dimensions, + elevation=elevation, + format=format, + size=size, + time=time, + transparent=transparent, + bgcolor=bgcolor, + exceptions=exceptions, + **kwargs) + return bind_url(base_url) + data def getfeatureinfo(self, layers=None, styles=None, From a767e292aad911423a93647ece5a301ddc3d785d Mon Sep 17 00:00:00 2001 From: sethg Date: Tue, 24 Nov 2026 18:43:01 +0100 Subject: [PATCH 4/4] Update and test usage and remove method and timeout params if passed --- docs/source/usage.rst | 20 ++++++++++++-------- owslib/map/wms111.py | 5 ++++- owslib/map/wms130.py | 5 ++++- tests/test_wms_getmap.py | 2 ++ 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/docs/source/usage.rst b/docs/source/usage.rst index d64f187c..c579a944 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -75,23 +75,27 @@ Result: ``getmap`` sends a blocking request. To fetch the image with another HTTP client, such as ``aiohttp`` in an ``asyncio`` application, ``buildGetMapURL`` takes the same parameters and returns the URL without sending a request. -For example, the latest radar frame from MSC GeoMet: +For example, the latest radar frame from MSC GeoMet, run in the asyncio REPL, which allows top-level ``await``: -.. code-block:: python +.. code-block:: console + + $ python -m asyncio + +.. code-block:: pycon >>> import aiohttp + >>> from owslib.wms import WebMapService >>> wms = WebMapService('https://geo.weather.gc.ca/geomet?layer=RADAR_1KM_RRAI', version='1.3.0') >>> url = wms.buildGetMapURL(layers=['RADAR_1KM_RRAI'], - srs='CRS:84', - bbox=(-95, 41, -73, 57), - size=(800, 600), - format='image/png', - time=wms['RADAR_1KM_RRAI'].defaulttimeposition) + ... srs='CRS:84', + ... bbox=(-95, 41, -73, 57), + ... size=(800, 600), + ... format='image/png', + ... time=wms['RADAR_1KM_RRAI'].defaulttimeposition) >>> async with aiohttp.ClientSession() as session: ... async with session.get(url) as response: ... png = await response.read() - WFS --- Connect to a WFS and inspect its capabilities. diff --git a/owslib/map/wms111.py b/owslib/map/wms111.py index 33483ca1..c8207051 100644 --- a/owslib/map/wms111.py +++ b/owslib/map/wms111.py @@ -279,8 +279,11 @@ def buildGetMapURL(self, layers=None, styles=None, srs=None, bbox=None, ): """Return the URL that getmap(method='Get') would request, without sending it. - Takes the same parameters as getmap(), except method and timeout. + Takes the same parameters as getmap(). method and timeout are accepted + so a shared parameter dict can be passed to both, but are ignored. """ + kwargs.pop('method', None) + kwargs.pop('timeout', None) base_url, data = self.__build_getmap_url( 'Get', layers=layers, diff --git a/owslib/map/wms130.py b/owslib/map/wms130.py index 01792a4a..fedd8ad2 100644 --- a/owslib/map/wms130.py +++ b/owslib/map/wms130.py @@ -340,8 +340,11 @@ def buildGetMapURL(self, layers=None, ): """Return the URL that getmap(method='Get') would request, without sending it. - Takes the same parameters as getmap(), except method and timeout. + Takes the same parameters as getmap(). method and timeout are accepted + so a shared parameter dict can be passed to both, but are ignored. """ + kwargs.pop('method', None) + kwargs.pop('timeout', None) base_url, data = self.__build_getmap_url( 'Get', layers=layers, diff --git a/tests/test_wms_getmap.py b/tests/test_wms_getmap.py index 5b2a2638..0606e0aa 100644 --- a/tests/test_wms_getmap.py +++ b/tests/test_wms_getmap.py @@ -52,6 +52,8 @@ def test_build_getmap_url(version, caps): wms.getmap(**params) assert wms.buildGetMapURL(**params) == wms.request + # method and timeout are ignored, and not sent as vendor params + assert wms.buildGetMapURL(**params, method='Get', timeout=30) == wms.request @pytest.mark.online