def getrecordbyid(self, id=[], esn='full', outputschema=namespaces['csw'], format=outputformat): """ Construct and process a GetRecordById request Parameters ---------- - id: the list of Ids - esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'full') - outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2') - format: the outputFormat (default is 'application/xml') """ # construct request data = { 'service': self.service, 'version': self.version, 'request': 'GetRecordById', 'outputFormat': format, 'outputSchema': outputschema, 'elementsetname': esn, 'id': ','.join(id), } self.request = '%s%s' % (bind_url(self.url), urlencode(data)) self._invoke() if self.exceptionreport is None: self.results = {} self.records = OrderedDict() self._parserecords(outputschema, esn)
def getrecordbyid(self, id=[], esn="full", outputschema=namespaces["csw"], format=outputformat): """ Construct and process a GetRecordById request Parameters ---------- - id: the list of Ids - esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'full') - outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2') - format: the outputFormat (default is 'application/xml') """ # construct request data = { "service": self.service, "version": self.version, "request": "GetRecordById", "outputFormat": format, "outputSchema": outputschema, "elementsetname": esn, "id": "", } self.request = "%s%s%s" % (bind_url(self.url), urlencode(data), ",".join(id)) self._invoke() if self.exceptionreport is None: self.results = {} self.records = {} self._parserecords(outputschema, esn)
def get_capabilities_url(self): if self.resource_type.startswith('OGC:') \ and self.resource_type != 'OGC:STA': url = '%s%s' % (bind_url(self.url), RESOURCE_TYPES[self.resource_type]['capabilities']) else: url = self.url return url
def get_capabilities_url(self): if self.resource_type.startswith('OGC:') \ and self.resource_type != 'OGC:STA': url = '%s%s' % (bind_url( self.url), RESOURCE_TYPES[self.resource_type]['capabilities']) else: url = self.url return url
def Subgetmap_url(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', method='Get', timeout=None, **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 request = {'version': self.version, 'request': 'GetMap'} 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) data = urlencode(request) ########## #Replace + with %20 ########## data = data.replace("+", "%20") request = bind_url(base_url) + data # GetMap validity u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # check for service exceptions, and return if u.info()['Content-Type'].split(';')[0] in [ 'application/vnd.ogc.se_xml' ]: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type( se_tree.find('ServiceException').text).strip() raise ServiceException(err_message) return request
def get_capabilities_url(self): if self.resource_type.startswith('OGC:') \ and self.resource_type not in \ ['OGC:STA', 'OGC:WFS3', 'ESRI:FS']: url = '%s%s' % (bind_url( self.url), RESOURCE_TYPES[self.resource_type]['capabilities']) else: url = self.url return url
def __init__(self, url, lang='en-US', version='2.0.2', timeout=10, skip_caps=False, username=None, password=None): """ Construct and process a GetCapabilities request Parameters ---------- - url: the URL of the CSW - lang: the language (default is 'en-US') - version: version (default is '2.0.2') - timeout: timeout in seconds - skip_caps: whether to skip GetCapabilities processing on init (default is False) - username: username for HTTP basic authentication - password: password for HTTP basic authentication """ self.url = url self.lang = lang self.version = version self.timeout = timeout self.username = username self.password = password self.service = 'CSW' self.exceptionreport = None self.owscommon = ows.OwsCommon('1.0.0') if not skip_caps: # process GetCapabilities # construct request data = {'service': self.service, 'version': self.version, 'request': 'GetCapabilities'} self.request = '%s%s' % (bind_url(self.url), urlencode(data)) self._invoke() if self.exceptionreport is None: # ServiceIdentification val = self._exml.find(util.nspath_eval('ows:ServiceIdentification', namespaces)) self.identification=ows.ServiceIdentification(val,self.owscommon.namespace) # ServiceProvider val = self._exml.find(util.nspath_eval('ows:ServiceProvider', namespaces)) self.provider=ows.ServiceProvider(val,self.owscommon.namespace) # ServiceOperations metadata self.operations=[] for elem in self._exml.findall(util.nspath_eval('ows:OperationsMetadata/ows:Operation', namespaces)): self.operations.append(ows.OperationsMetadata(elem, self.owscommon.namespace)) # FilterCapabilities val = self._exml.find(util.nspath_eval('ogc:Filter_Capabilities', namespaces)) self.filters=fes.FilterCapabilities(val)
def __init__(self, url, lang="en-US", version="2.0.2", timeout=10, skip_caps=False): """ Construct and process a GetCapabilities request Parameters ---------- - url: the URL of the CSW - lang: the language (default is 'en-US') - version: version (default is '2.0.2') - timeout: timeout in seconds - skip_caps: whether to skip GetCapabilities processing on init (default is False) """ self.url = url self.lang = lang self.version = version self.timeout = timeout self.service = "CSW" self.exceptionreport = None self.owscommon = ows.OwsCommon("1.0.0") if not skip_caps: # process GetCapabilities # construct request data = {"service": self.service, "version": self.version, "request": "GetCapabilities"} self.request = "%s%s" % (bind_url(self.url), urlencode(data)) self._invoke() if self.exceptionreport is None: # ServiceIdentification val = self._exml.find(util.nspath_eval("ows:ServiceIdentification", namespaces)) self.identification = ows.ServiceIdentification(val, self.owscommon.namespace) # ServiceProvider val = self._exml.find(util.nspath_eval("ows:ServiceProvider", namespaces)) self.provider = ows.ServiceProvider(val, self.owscommon.namespace) # ServiceOperations metadata self.operations = [] for elem in self._exml.findall(util.nspath_eval("ows:OperationsMetadata/ows:Operation", namespaces)): self.operations.append(ows.OperationsMetadata(elem, self.owscommon.namespace)) # FilterCapabilities val = self._exml.find(util.nspath_eval("ogc:Filter_Capabilities", namespaces)) self.filters = fes.FilterCapabilities(val)
def _invoke(self): # do HTTP request request_url = self.url # Get correct URL based on Operation list. # If skip_caps=True, then self.operations has not been set, so use # default URL. if hasattr(self, 'operations'): caller = inspect.stack()[1][3] if caller == 'getrecords2': caller = 'getrecords' try: op = self.get_operation_by_name(caller) if isinstance(self.request, six.string_types): # GET KVP get_verbs = [ x for x in op.methods if x.get('type').lower() == 'get' ] request_url = get_verbs[0].get('url') else: post_verbs = [ x for x in op.methods if x.get('type').lower() == 'post' ] if len(post_verbs) > 1: # Filter by constraints. We must match a PostEncoding of "XML" for pv in post_verbs: for const in pv.get('constraints'): if const.name.lower() == 'postencoding': values = [v.lower() for v in const.values] if 'xml' in values: request_url = pv.get('url') break else: # Well, just use the first one. request_url = post_verbs[0].get('url') elif len(post_verbs) == 1: request_post_url = post_verbs[0].get('url') except: # no such luck, just go with request_url pass if isinstance(self.request, six.string_types): # GET KVP self.request = '%s%s' % (bind_url(request_url), self.request) self.response = openURL(self.request, None, 'Get', username=self.username, password=self.password, timeout=self.timeout).read() else: self.request = cleanup_namespaces(self.request) # Add any namespaces used in the "typeNames" attribute of the # csw:Query element to the query's xml namespaces. for query in self.request.findall( util.nspath_eval('csw:Query', namespaces)): ns = query.get("typeNames", None) if ns is not None: # Pull out "gmd" from something like "gmd:MD_Metadata" from the list # of typenames ns_keys = [x.split(':')[0] for x in ns.split(' ')] self.request = add_namespaces(self.request, ns_keys) self.request = util.element_to_string(self.request, encoding='utf-8') self.response = util.http_post(request_url, self.request, self.lang, self.timeout, self.username, self.password) # parse result see if it's XML self._exml = etree.parse(BytesIO(self.response)) # it's XML. Attempt to decipher whether the XML response is CSW-ish """ valid_xpaths = [ util.nspath_eval('ows:ExceptionReport', namespaces), util.nspath_eval('csw:Capabilities', namespaces), util.nspath_eval('csw:DescribeRecordResponse', namespaces), util.nspath_eval('csw:GetDomainResponse', namespaces), util.nspath_eval('csw:GetRecordsResponse', namespaces), util.nspath_eval('csw:GetRecordByIdResponse', namespaces), util.nspath_eval('csw:HarvestResponse', namespaces), util.nspath_eval('csw:TransactionResponse', namespaces) ] if self._exml.getroot().tag not in valid_xpaths: raise RuntimeError('Document is XML, but not CSW-ish') # check if it's an OGC Exception val = self._exml.find(util.nspath_eval('ows:Exception', namespaces)) if val is not None: raise ows.ExceptionReport(self._exml, self.owscommon.namespace) else: self.exceptionreport = None
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): 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 # GetMap-Request 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=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 u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # check for service exceptions, and return if u.info()['Content-Type'] == 'XML': se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type( se_tree.find('ServiceException').text).strip() raise ServiceException(err_message) return u
def getmap(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, elevation=None, dimensions={}, transparent=False, bgcolor='#FFFFFF', exceptions='XML', method='Get', timeout=None, **kwargs): """Request and return an image from the WMS as a file-like object. Parameters ---------- layers : list List of content layer names. styles : list Optional list of named styles, must be the same length as the layers list. srs : string A spatial reference system identifier. Note: this is an invalid query parameter key for 1.3.0 but is being retained for standardization with 1.1.1. Note: throws exception if the spatial ref is ESRI's "no reference" code (EPSG:0) bbox : tuple (left, bottom, right, top) in srs units (note, this order does not change depending on axis order of the crs). CRS:84: (long, lat) EPSG:4326: (lat, long) format : string Output image format such as 'image/jpeg'. size : tuple (width, height) in pixels. time : string or list or range Optional. Time value of the specified layer as ISO-8601 (per value) elevation : string or list or range Optional. Elevation value of the specified layer. dimensions: dict (dimension : string or list or range) Optional. Any other Dimension option, as specified in the GetCapabilities transparent : bool Optional. Transparent background if True. bgcolor : string Optional. Image background color. method : string Optional. HTTP DCP method name: Get or Post. **kwargs : extra arguments anything else e.g. vendor specific parameters Example ------- wms = WebMapService('http://webservices.nationalatlas.gov/wms/1million',\ version='1.3.0') img = wms.getmap(layers=['airports1m'],\ styles=['default'],\ srs='EPSG:4326',\ bbox=(-176.646, 17.7016, -64.8017, 71.2854),\ size=(300, 300),\ format='image/jpeg',\ transparent=True) out = open('example.jpg.jpg', 'wb') out.write(img.read()) 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 = 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) data = urlencode(request) self.request = bind_url(base_url) + data u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # need to handle casing in the header keys headers = {} for k, v in six.iteritems(u.info()): headers[k.lower()] = v # handle the potential charset def if headers['content-type'].split(';')[0] in [ 'application/vnd.ogc.se_xml', 'text/xml' ]: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type( se_tree.find(nspath('ServiceException', OGC_NAMESPACE)).text).strip() raise ServiceException(err_message) return u
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 ): 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 # GetMap-Request 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=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 u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # check for service exceptions, and return if u.info()['Content-Type'] == 'XML': se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find('ServiceException').text).strip() raise ServiceException(err_message) return u
def getmap(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, elevation=None, dimensions={}, transparent=False, bgcolor='#FFFFFF', exceptions='XML', method='Get', timeout=None, **kwargs ): """Request and return an image from the WMS as a file-like object. Parameters ---------- layers : list List of content layer names. styles : list Optional list of named styles, must be the same length as the layers list. srs : string A spatial reference system identifier. Note: this is an invalid query parameter key for 1.3.0 but is being retained for standardization with 1.1.1. Note: throws exception if the spatial ref is ESRI's "no reference" code (EPSG:0) bbox : tuple (left, bottom, right, top) in srs units (note, this order does not change depending on axis order of the crs). CRS:84: (long, lat) EPSG:4326: (lat, long) format : string Output image format such as 'image/jpeg'. size : tuple (width, height) in pixels. time : string or list or range Optional. Time value of the specified layer as ISO-8601 (per value) elevation : string or list or range Optional. Elevation value of the specified layer. dimensions: dict (dimension : string or list or range) Optional. Any other Dimension option, as specified in the GetCapabilities transparent : bool Optional. Transparent background if True. bgcolor : string Optional. Image background color. method : string Optional. HTTP DCP method name: Get or Post. **kwargs : extra arguments anything else e.g. vendor specific parameters Example ------- wms = WebMapService('http://webservices.nationalatlas.gov/wms/1million',\ version='1.3.0') img = wms.getmap(layers=['airports1m'],\ styles=['default'],\ srs='EPSG:4326',\ bbox=(-176.646, 17.7016, -64.8017, 71.2854),\ size=(300, 300),\ format='image/jpeg',\ transparent=True) out = open('example.jpg.jpg', 'wb') out.write(img.read()) 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 = 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) data = urlencode(request) self.request = bind_url(base_url) + data u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # need to handle casing in the header keys headers = {} for k, v in six.iteritems(u.info()): headers[k.lower()] = v # handle the potential charset def if headers['content-type'].split(';')[0] in ['application/vnd.ogc.se_xml', 'text/xml']: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find(nspath('ServiceException', OGC_NAMESPACE)).text).strip() raise ServiceException(err_message) return u
def getlegendgraphic(self, layer=None, styles=None, format=None, size=None, time=None, transparent=False, bgcolor='#FFFFFF', exceptions='application/vnd.ogc.se_xml', method='Get', timeout=None, **kwargs): # Extract legend url from layer styles request = None request = self.contents[layer].getlegendgraphicrequest() # Construct legend url if request is None: try: base_url = next((m.get('url') for m in self.getOperationByName( 'GetLegendGraphic').methods if m.get('type').lower() == method.lower())) except StopIteration: base_url = self.url request = {'version': self.version, 'request': 'GetLegendGraphic'} request = self.__build_getlegendgraphic_request( layer=layer, styles=styles, format=format, size=size, time=time, transparent=transparent, bgcolor=bgcolor, exceptions=exceptions, **kwargs) data = urlencode(request) ########## #Replace + with %20 ########## data = data.replace("+", "%20") request = bind_url(base_url) + data u = openURL(request, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # check for service exceptions, and return if u.info()['Content-Type'].split(';')[0] in [ 'application/vnd.ogc.se_xml' ]: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type( se_tree.find('ServiceException').text).strip() + request raise ServiceException(err_message) return u, request
def getmap(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', method='Get', timeout=None, **kwargs ): """Request and return an image from the WMS as a file-like object. Parameters ---------- layers : list List of content layer names. styles : list Optional list of named styles, must be the same length as the layers list. srs : string A spatial reference system identifier. bbox : tuple (left, bottom, right, top) in srs units. format : string Output image format such as 'image/jpeg'. size : tuple (width, height) in pixels. transparent : bool Optional. Transparent background if True. bgcolor : string Optional. Image background color. method : string Optional. HTTP DCP method name: Get or Post. **kwargs : extra arguments anything else e.g. vendor specific parameters Example ------- wms = WebMapService('http://giswebservices.massgis.state.ma.us/geoserver/wms', version='1.1.1') img = wms.getmap(layers=['massgis:GISDATA.SHORELINES_ARC'],\ styles=[''],\ srs='EPSG:4326',\ bbox=(-70.8, 42, -70, 42.8),\ size=(300, 300),\ format='image/jpeg',\ transparent=True) out = open('example.jpg', 'wb') bytes_written = out.write(img.read()) 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( layers=layers, styles=styles, srs=srs, bbox=bbox, format=format, size=size, time=time, transparent=transparent, bgcolor=bgcolor, 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) # check for service exceptions, and return if u.info().get('Content-Type', '').split(';')[0] in ['application/vnd.ogc.se_xml']: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find('ServiceException').text).strip() raise ServiceException(err_message) return u
def getmap(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', method='Get', timeout=None, **kwargs ): """Request and return an image from the WMS as a file-like object. Parameters ---------- layers : list List of content layer names. styles : list Optional list of named styles, must be the same length as the layers list. srs : string A spatial reference system identifier. bbox : tuple (left, bottom, right, top) in srs units. format : string Output image format such as 'image/jpeg'. size : tuple (width, height) in pixels. transparent : bool Optional. Transparent background if True. bgcolor : string Optional. Image background color. method : string Optional. HTTP DCP method name: Get or Post. **kwargs : extra arguments anything else e.g. vendor specific parameters Example ------- wms = WebMapService('http://giswebservices.massgis.state.ma.us/geoserver/wms', version='1.1.1') img = wms.getmap(layers=['massgis:GISDATA.SHORELINES_ARC'],\ styles=[''],\ srs='EPSG:4326',\ bbox=(-70.8, 42, -70, 42.8),\ size=(300, 300),\ format='image/jpeg',\ transparent=True) out = open('example.jpg', 'wb') bytes_written = out.write(img.read()) 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( layers=layers, styles=styles, srs=srs, bbox=bbox, format=format, size=size, time=time, transparent=transparent, bgcolor=bgcolor, exceptions=exceptions, **kwargs) data = urlencode(request) self.request = bind_url(base_url) + data u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # check for service exceptions, and return if u.info().get('Content-Type', '').split(';')[0] in ['application/vnd.ogc.se_xml']: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find('ServiceException').text).strip() raise ServiceException(err_message) return u
def _invoke(self): # do HTTP request request_url = self.url # Get correct URL based on Operation list. # If skip_caps=True, then self.operations has not been set, so use # default URL. if hasattr(self, 'operations'): caller = inspect.stack()[1][3] if caller == 'getrecords2': caller = 'getrecords' try: op = self.get_operation_by_name(caller) if isinstance(self.request, six.string_types): # GET KVP get_verbs = [x for x in op.methods if x.get('type').lower() == 'get'] request_url = get_verbs[0].get('url') else: post_verbs = [x for x in op.methods if x.get('type').lower() == 'post'] if len(post_verbs) > 1: # Filter by constraints. We must match a PostEncoding of "XML" for pv in post_verbs: for const in pv.get('constraints'): if const.name.lower() == 'postencoding': values = [v.lower() for v in const.values] if 'xml' in values: request_url = pv.get('url') break else: # Well, just use the first one. request_url = post_verbs[0].get('url') elif len(post_verbs) == 1: request_url = post_verbs[0].get('url') except: # no such luck, just go with request_url pass if isinstance(self.request, six.string_types): # GET KVP self.request = '%s%s' % (bind_url(request_url), self.request) self.response = openURL(self.request, None, 'Get', username=self.username, password=self.password, timeout=self.timeout).read() else: self.request = cleanup_namespaces(self.request) # Add any namespaces used in the "typeNames" attribute of the # csw:Query element to the query's xml namespaces. for query in self.request.findall(util.nspath_eval('csw:Query', namespaces)): ns = query.get("typeNames", None) if ns is not None: # Pull out "gmd" from something like "gmd:MD_Metadata" from the list # of typenames ns_keys = [x.split(':')[0] for x in ns.split(' ')] self.request = add_namespaces(self.request, ns_keys) self.request = util.element_to_string(self.request, encoding='utf-8') self.response = util.http_post(request_url, self.request, self.lang, self.timeout, self.username, self.password) # parse result see if it's XML self._exml = etree.parse(BytesIO(self.response)) # it's XML. Attempt to decipher whether the XML response is CSW-ish """ valid_xpaths = [ util.nspath_eval('ows:ExceptionReport', namespaces), util.nspath_eval('csw:Capabilities', namespaces), util.nspath_eval('csw:DescribeRecordResponse', namespaces), util.nspath_eval('csw:GetDomainResponse', namespaces), util.nspath_eval('csw:GetRecordsResponse', namespaces), util.nspath_eval('csw:GetRecordByIdResponse', namespaces), util.nspath_eval('csw:HarvestResponse', namespaces), util.nspath_eval('csw:TransactionResponse', namespaces) ] if self._exml.getroot().tag not in valid_xpaths: raise RuntimeError('Document is XML, but not CSW-ish') # check if it's an OGC Exception val = self._exml.find(util.nspath_eval('ows:Exception', namespaces)) if val is not None: raise ows.ExceptionReport(self._exml, self.owscommon.namespace) else: self.exceptionreport = None
def Subgetmap_url(self, layers=None, styles=None, srs=None, bbox=None, format=None, size=None, time=None, elevation=None, dimensions={}, transparent=False, bgcolor='#FFFFFF', exceptions='XML', method='Get', timeout=None, **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 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) data = urlencode(request) data = data.replace("+", "%20") request = bind_url(base_url) + data u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # need to handle casing in the header keys headers = {} for k, v in six.iteritems(u.info()): headers[k.lower()] = v # handle the potential charset def if headers['content-type'].split(';')[0] in [ 'application/vnd.ogc.se_xml', 'text/xml' ]: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type( se_tree.find( subcommon.nspath('ServiceException', OGC_NAMESPACE)).text).strip() raise ServiceException(err_message) return request
def _invoke(self, mock_requests_post, mock_requests_request): try: if self.auth.token is not None: self.auth.username = "******" self.auth.password = self.auth.token except AttributeError: pass # do HTTP request request_url = self.url # Get correct URL based on Operation list. # If skip_caps=True, then self.operations has not been set, so use # default URL. if hasattr(self, "operations"): caller = inspect.stack()[1][3] if caller == "getrecords2": caller = "getrecords" # noinspection PyBroadException try: op = self.get_operation_by_name(caller) if isinstance(self.request, str): # GET KVP get_verbs = [ x for x in op.methods if x.get("type").lower() == "get" ] request_url = get_verbs[0].get("url") else: post_verbs = [ x for x in op.methods if x.get("type").lower() == "post" ] if len(post_verbs) > 1: # Filter by constraints. We must match a PostEncoding of "XML" for pv in post_verbs: for const in pv.get("constraints"): if const.name.lower() == "postencoding": values = [v.lower() for v in const.values] if "xml" in values: request_url = pv.get("url") break else: # Well, just use the first one. request_url = post_verbs[0].get("url") elif len(post_verbs) == 1: request_url = post_verbs[0].get("url") except Exception: # nosec # no such luck, just go with request_url pass # print("Echo") if isinstance(self.request, str): # GET KVP # print("Foxtrot") self.request = "%s%s" % (bind_url(request_url), self.request) self.response = openURL(self.request, None, "Get", timeout=self.timeout, auth=self.auth).read() # debug # print("invoke") # print(self.response[0:100]) else: # print("Golf") self.request = cleanup_namespaces(self.request) # Add any namespaces used in the "typeNames" attribute of the # csw:Query element to the query's xml namespaces. # noinspection PyUnresolvedReferences for query in self.request.findall( util.nspath_eval("csw:Query", csw_namespaces)): ns = query.get("typeNames", None) if ns is not None: # Pull out "gmd" from something like "gmd:MD_Metadata" from the list # of typenames ns_keys = [x.split(":")[0] for x in ns.split(" ")] self.request = add_namespaces(self.request, ns_keys) self.request = add_namespaces(self.request, "ows") self.request = util.element_to_string(self.request, encoding="utf-8") # print("Hotel") self.response = http_post(request_url, self.request, self.lang, self.timeout, auth=self.auth) # debug # print("invoke 2") # print(self.response[0:100]) # debug # print("parse") # print(self.response[0:100]) # print(self.response) # parse result see if it's XML self._exml = etree.parse(BytesIO(self.response)) # it's XML. Attempt to decipher whether the XML response is CSW-ish """ valid_xpaths = [ util.nspath_eval("ows:ExceptionReport", csw_namespaces), util.nspath_eval("csw:Capabilities", csw_namespaces), util.nspath_eval("csw:DescribeRecordResponse", csw_namespaces), util.nspath_eval("csw:GetDomainResponse", csw_namespaces), util.nspath_eval("csw:GetRecordsResponse", csw_namespaces), util.nspath_eval("csw:GetRecordByIdResponse", csw_namespaces), util.nspath_eval("csw:HarvestResponse", csw_namespaces), util.nspath_eval("csw:TransactionResponse", csw_namespaces), ] if self._exml.getroot().tag not in valid_xpaths: raise RuntimeError("Document is XML, but not CSW-ish") # check if it's an OGC Exception val = self._exml.find(util.nspath_eval("ows:Exception", csw_namespaces)) if val is not None: raise ows.ExceptionReport(self._exml, self.owscommon.namespace) else: self.exceptionreport = None
def getlegendgraphic(self, layer=None, style=None, format=None, size=None, exceptions='XML', method='Get', timeout=None, **kwargs ): """Request and return an image from the WMS as a file-like object. Parameters ---------- layer : string Content layer name. style : string Named style. format : string Output image format such as 'image/jpeg'. width : integer width in pixels. height : integer height in pixels. method : string Optional. HTTP DCP method name: Get or Post. **kwargs : extra arguments anything else e.g. vendor specific parameters Example ------- wms = WebMapService('http://webservices.nationalatlas.gov/wms/1million',\ version='1.3.0') img = wms.getlegendgraphic(layer='airports1m',\ style='default',\ size=[300, 300],\ format='image/jpeg',\ out = open('example.jpg', 'wb') out.write(img.read()) 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 = self.__build_getlegendgraphic_request( layer=layer, style=style, format=format, size=size, exceptions=exceptions, **kwargs) data = urlencode(request) self.request = bind_url(base_url) + data u = openURL(base_url, data, method, username=self.username, password=self.password, timeout=timeout or self.timeout) # need to handle casing in the header keys headers = {} for k, v in six.iteritems(u.info()): headers[k.lower()] = v # handle the potential charset def if headers['content-type'].split(';')[0] in ['application/vnd.ogc.se_xml', 'text/xml']: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find(nspath('ServiceException', OGC_NAMESPACE)).text).strip() raise ServiceException(err_message) return u