本文整理汇总了Python中owslib.wms.WebMapService.getOperationByName方法的典型用法代码示例。如果您正苦于以下问题:Python WebMapService.getOperationByName方法的具体用法?Python WebMapService.getOperationByName怎么用?Python WebMapService.getOperationByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类owslib.wms.WebMapService
的用法示例。
在下文中一共展示了WebMapService.getOperationByName方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HandleWMS
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
class HandleWMS():
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 get_service_url(self, method='Get'):
return self.wms.getOperationByName('GetMap').methods[method]['url']
def get_format_options(self, format='image/png'):
formats = self.wms.getOperationByName('GetMap').formatOptions
if format in formats:
return format
else:
return formats
def get_srs(self, layer, srs='EPSG:4326'):
this_layer = self.wms[layer]
srs_list = this_layer.crsOptions
if srs in srs_list:
return srs
else:
return "SRS Not Found"
def get_bbox(self, layer):
this_layer = self.wms[layer]
return this_layer.boundingBoxWGS84
def do_layer_check(self, resource):
layer_list = list(self.wms.contents)
this_layer = resource.get("layer")
try:
first_layer = layer_list[0]
if this_layer in layer_list:
return this_layer
elif this_layer.lower() in layer_list:
return this_layer.lower()
else:
return first_layer
except Exception:
pass
def get_layer_info(self, data_dict):
layer = self.do_layer_check(data_dict)
bbox = self.get_bbox(layer)
srs = self.get_srs(layer)
format = self.get_format_options()
service_url = self.get_service_url()
return {
'layer': layer,
'bbox': bbox,
'srs': srs,
'format': format,
'service_url': service_url
}
示例2: check_advertised_wms_layers
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
def check_advertised_wms_layers(self):
"""
Makes a GetMap request for each layer advertised by WMS service.
An exception is raised on failure.
| Check advertised wms layers |
"""
wms = WebMapService(self._url, version=self._ogc_version)
for layer in wms.contents.values():
wms.getmap(
layers=[layer.name],
srs=layer.crsOptions[0],
bbox=layer.boundingBox[0:-1],
size=(300, 300),
format=wms.getOperationByName('GetMap').formatOptions[0])
示例3: _process_wms_service
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
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', 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)
示例4: get_full_map
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
def get_full_map(uri, base_name=None, layers=None, size=(300,300)):
print 'Get map for %s' % uri
# Get the wms object
wms = WebMapService(uri)
# Get random layer if not specified
if not layers:
layers = list(wms.contents)
# Set to maximum 5 layers
if len(layers) > 5:
layers = random.sample(layers, 5)
print 'layers', layers
# Set crs
srs='EPSG:4326'
# Get bounding box of the layers
bbox = wms.contents[layers[0]].boundingBoxWGS84
print 'bbox', bbox
# Get image formats
image_formats = wms.getOperationByName('GetMap').formatOptions
if 'image/png' in image_formats:
image_format = 'image/png'
elif 'image/jpeg' in image_formats:
image_format = 'image/jpeg'
else:
image_format = image_formats[0]
print 'image_format', image_format
styles = []
image = None
try:
image = retrieve_map_owslib(uri, bbox, srs, size, image_format, styles, layers, wms)
except Exception, e:
print 'Can not use retrieve_map_owslib because %s' % e
示例5: test_service
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
def test_service(record, output, format_type):
"""Test given service based on configuration record
dictionary with at least 'url' attribute
"""
url = record["url"]
# version = '1.3.0'
# if record.get('version'):
# version = record['version']
log_file = open(LOG, "a")
log_file.write(url + "\n")
log_file.close()
exception = None
result = True
layers = []
service = None
title = None
try:
service = WebMapService(url)
except Exception as e:
result = False
exception = traceback.format_exc()
if "title" in record:
title = record["title"]
if service:
if record.get("use_service_url"):
method = next(
(
getmap_method
for getmap_method in service.getOperationByName("GetMap").methods
if getmap_method["type"].lower() == "get"
)
)
method["url"] = service.url
layers = None
if "layers" in record:
layers = record["layers"]
layers = test_layers(service, layers)
for layer in layers:
if not layers[layer]["is_image"]:
result = False
result = {
"id": str(uuid.uuid4()),
"url": url,
"title": title,
"layers": layers,
"passed": result,
"exception": exception,
}
make_report(output, result, format_type)
return result
示例6: HandleWMS
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
class HandleWMS():
"""
Processor for WMS resources. Requires a getCapabilities URL for the WMS and a WMS version passed in as a string.
For now, only WMS v1.1.1 is supported by OWSLib.
"""
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)
# Return a specific service URL, getMap is default
def get_service_url(self, method='Get'):
return self.wms.getOperationByName('GetMap').methods[method]['url']
# Return an image format, *.png is default
def get_format_options(self, format='image/png'):
formats = self.wms.getOperationByName('GetMap').formatOptions
if format in formats:
return format
else:
return formats
# Return a spatial reference system, default is WGS84
def get_srs(self, layer, srs='EPSG:4326'):
this_layer = self.wms[layer]
srs_list = this_layer.crsOptions
if srs in srs_list:
return srs
else:
return "SRS Not Found"
# Return bounding box of the service
def get_bbox(self, layer):
this_layer = self.wms[layer]
return this_layer.boundingBoxWGS84
# Pass in a dictionary with the layer name bound to 'layer'. If the 'layer' is not found, then just return the
# first layer in the list of available layers
def do_layer_check(self, data_dict):
layer_list = list(self.wms.contents)
resource = data_dict.get("resource", {})
this_layer = resource.get("layer")
try:
first_layer = layer_list[0]
if this_layer in layer_list:
return this_layer
elif this_layer.lower() in layer_list:
return this_layer.lower()
else:
return first_layer
except Exception:
pass
# Return all of the information we need to access features in a WMS as one dictionary
def get_layer_info(self, data_dict):
layer = self.do_layer_check(data_dict)
bbox = self.get_bbox(layer)
srs = self.get_srs(layer)
format = self.get_format_options()
service_url = self.get_service_url()
return {
'layer': layer,
'bbox': bbox,
'srs': srs,
'format': format,
'service_url': service_url
}
示例7: assert
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
assert(wms_lyr.queryable)
# SRS
print("Available SRS: ", wms_lyr.crsOptions)
if current_crs in wms_lyr.crsOptions:
print("It's a SRS match! With map canvas: " + current_crs)
srs = current_crs
elif "EPSG:4326" in wms_lyr.crsOptions:
print("It's a SRS match! With standard WGS 84 (EPSG:4326)")
srs = "EPSG:4326"
else:
print("Searched SRS not available within service CRS.")
srs = ""
# Format definition
wms_lyr_formats = wms.getOperationByName('GetMap').formatOptions
formats_image = [f.split(" ", 1)[0] for f in wms_lyr_formats
if f in qgis_wms_formats]
if "image/png" in formats_image:
layer_format = "image/png"
elif "image/jpeg" in formats_image:
layer_format = "image/jpeg"
else:
layer_format = formats_image[0]
# Style definition
print("Available styles: ", wms_lyr.styles)
lyr_style = wms_lyr.styles.keys()[0]
# GetMap URL
wms_lyr_url = wms.getOperationByName('GetMap').methods
示例8: update_thumbnail
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
def update_thumbnail(self):
print 'Generating thumbnail for layer id %s' % self.id
if not self.has_valid_bbox():
raise ValueError('Extent for this layer is invalid, cannot generate thumbnail')
return None
format_error_message = 'This layer does not expose valid formats (png, jpeg) to generate the thumbnail'
img = None
if self.service.type == 'OGC_WMS':
ows = WebMapService(self.service.url)
op_getmap = ows.getOperationByName('GetMap')
image_format = 'image/png'
if image_format not in op_getmap.formatOptions:
if 'image/jpeg' in op_getmap.formatOptions:
image_format = 'image/jpeg'
else:
raise NotImplementedError(format_error_message)
img = ows.getmap(
layers=[self.name],
srs='EPSG:4326',
bbox=(
float(self.bbox_x0),
float(self.bbox_y0),
float(self.bbox_x1),
float(self.bbox_y1)
),
size=(50, 50),
format=image_format,
transparent=True
)
if 'ogc.se_xml' in img.info()['Content-Type']:
raise ValueError(img.read())
img = None
elif self.service.type == 'OGC_WMTS':
ows = WebMapTileService(self.service.url)
ows_layer = ows.contents[self.name]
image_format = 'image/png'
if image_format not in ows_layer.formats:
if 'image/jpeg' in ows_layer.formats:
image_format = 'image/jpeg'
else:
raise NotImplementedError(format_error_message)
img = ows.gettile(
layer=self.name,
tilematrixset=ows_layer.tilematrixsets[0],
tilematrix='0',
row='0',
column='0',
format=image_format
)
elif self.service.type == 'WM':
ows = WebMapService(self.url, username=settings.WM_USERNAME, password=settings.WM_PASSWORD)
op_getmap = ows.getOperationByName('GetMap')
image_format = 'image/png'
if image_format not in op_getmap.formatOptions:
if 'image/jpeg' in op_getmap.formatOptions:
image_format = 'image/jpeg'
else:
raise NotImplementedError(format_error_message)
img = ows.getmap(
layers=[self.name],
srs='EPSG:4326',
bbox=(
float(self.bbox_x0),
float(self.bbox_y0),
float(self.bbox_x1),
float(self.bbox_y1)
),
size=(50, 50),
format=image_format,
transparent=True
)
if 'ogc.se_xml' in img.info()['Content-Type']:
raise ValueError(img.read())
img = None
elif self.service.type == 'WARPER':
ows = WebMapService(self.url)
op_getmap = ows.getOperationByName('GetMap')
image_format = 'image/png'
if image_format not in op_getmap.formatOptions:
if 'image/jpeg' in op_getmap.formatOptions:
image_format = 'image/jpeg'
else:
raise NotImplementedError(format_error_message)
img = ows.getmap(
layers=[self.name],
srs='EPSG:4326',
bbox=(
float(self.bbox_x0),
float(self.bbox_y0),
float(self.bbox_x1),
float(self.bbox_y1)
),
size=(50, 50),
format=image_format,
transparent=True
)
if 'ogc.se_xml' in img.info()['Content-Type']:
raise ValueError(img.read())
img = None
#.........这里部分代码省略.........
示例9: build_wms_url
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
#.........这里部分代码省略.........
try:
wms_lyr = wms[layer_name]
except KeyError as e:
logger.error("Layer {} not found in WMS service: {}"
.format(layer_name,
wms_url_getcap))
return (0,
"Layer {} not found in WMS service: {}"
.format(layer_name,
wms_url_getcap), e)
# SRS definition
srs_map = plg_tools.get_map_crs()
srs_lyr_new = qsettings.value("/Projections/defaultBehaviour")
srs_lyr_crs = qsettings.value("/Projections/layerDefaultCrs")
srs_qgs_new = qsettings.value("/Projections/projectDefaultCrs")
srs_qgs_otf_on = qsettings.value("/Projections/otfTransformEnabled")
srs_qgs_otf_auto = qsettings.value("/Projections/otfTransformAutoEnable")
# DEV
# print("CRS: ", wms_lyr.crsOptions,
# "For new layers: " + srs_lyr_new + srs_lyr_crs,
# "For new projects: " + srs_qgs_new,
# "OTF enabled: " + srs_qgs_otf_on,
# "OTF smart enabled: " + srs_qgs_otf_auto,
# "Map canvas SRS:" + plg_tools.get_map_crs())
self.cached_wms["CRS"] = wms_lyr.crsOptions
if srs_map in wms_lyr.crsOptions:
logger.debug("It's a SRS match! With map canvas: " + srs_map)
srs = srs_map
elif srs_qgs_new in wms_lyr.crsOptions\
and srs_qgs_otf_on == "false"\
and srs_qgs_otf_auto == "false":
logger.debug("It's a SRS match! With default new project: " + srs_qgs_new)
srs = srs_qgs_new
elif srs_lyr_crs in wms_lyr.crsOptions and srs_lyr_new == "useGlobal":
logger.debug("It's a SRS match! With default new layer: " + srs_lyr_crs)
srs = srs_lyr_crs
elif "EPSG:4326" in wms_lyr.crsOptions:
logger.debug("It's a SRS match! With standard WGS 84 (EPSG:4326)")
srs = "EPSG:4326"
else:
logger.debug("Map Canvas SRS not available within service CRS.")
srs = wms_lyr.crsOptions[0]
# Format definition
wms_lyr_formats = wms.getOperationByName('GetMap').formatOptions
formats_image = [f.split(" ", 1)[0] for f in wms_lyr_formats
if f in qgis_wms_formats]
self.cached_wms["formats"] = formats_image
if "image/png" in formats_image:
layer_format = "image/png"
elif "image/jpeg" in formats_image:
layer_format = "image/jpeg"
else:
layer_format = formats_image[0]
# Style definition
lyr_style = wms_lyr.styles.keys()[0]
# GetMap URL
wms_lyr_url = wms.getOperationByName('GetMap').methods
wms_lyr_url = wms_lyr_url[0].get("url")
if wms_lyr_url[-1] == "&":
wms_lyr_url = wms_lyr_url[:-1]
else:
pass
self.cached_wms["url"] = wms_lyr_url
# url construction
try:
wms_url_params = {"SERVICE": "WMS",
"VERSION": srv_details.get("formatVersion", "1.3.0"),
"REQUEST": "GetMap",
"layers": layer_name,
"crs": srs,
"format": layer_format,
"styles": "",
# "styles": lyr_style,
# "url": srv_details.get("path"),
"url": wms_lyr_url,
}
wms_url_final = unquote(urlencode(wms_url_params, "utf8"))
except UnicodeEncodeError:
wms_url_params = {"SERVICE": "WMS",
"VERSION": srv_details.get("formatVersion", "1.3.0"),
"REQUEST": "GetMap",
"layers": layer_name.decode("latin1"),
"crs": srs,
"format": layer_format,
"styles": "",
# "styles": lyr_style,
# "url": srv_details.get("path"),
"url": wms_lyr_url,
}
wms_url_final = unquote(urlencode(wms_url_params, "utf8"))
# method ending
return ["WMS", layer_title, wms_url_final]
else:
return None
示例10: WMSDataServiceToReclineJS
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
class WMSDataServiceToReclineJS():
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 get_layers(self):
return list(self.wms.contents)
def get_srs(self, layer, srs='EPSG:4326'):
thisSRS = srs
thisLayer = self.wms[layer]
srsList = thisLayer.crsOptions
if thisSRS in srsList:
return thisSRS
else:
return thisSRS + " not found"
def get_service_operations(self):
thisWMS = self.wms.operations
return [op.name for op in thisWMS]
def get_service_methods(self):
thisWMS = self.wms.getOperationByName('GetMap').methods
return thisWMS
def get_GET_url(self):
methods = self.get_service_methods()
return methods['Get']['url']
def get_service_format_options(self, format='image/png'):
thisFormat = format
thisWMS = self.wms.getOperationByName('GetMap').formatOptions
if thisFormat in thisWMS:
return thisFormat
else:
return thisWMS
def get_layer_details(self, layer):
keys = ['layer', 'bbox', 'srs', 'format']
thisLayer = self.wms[layer]
bbox = thisLayer.boundingBoxWGS84
thisSRS = self.get_srs(layer)
return dict(zip(keys,[thisLayer,bbox,thisSRS,'none']))
def get_service_url(self, layer):
thisFormat = self.get_service_format_options(format)
layer_details = self.get_layer_details(layer)
serviceURL = self.wms.getmap(layers=[layer],
srs=layer_details['srs'],
bbox=layer_details['bbox'],
size=self.size,
format=thisFormat)
return serviceURL
def hack_up_a_layer_name(self, data_dict):
data = data_dict.get("resource")
if data.get("layer_name"):
return data.get("layer_name")
elif data.get("layer"):
return data.get("layer")
elif data.get("layers"):
return data.get("layers")
else:
try:
layer_list = self.get_layers()
return layer_list[0]
except:
return "Sorry, can't find a layer!"
def recline_ogc_wms(self, data_dict):
data = data_dict
keys = ["layer", "url"]
layer = self.hack_up_a_layer_name(data)
url = self.get_GET_url()
return dict(zip(keys,[layer,url]))
def ogc_wms_variables(self, data_dict):
data
示例11: test_wms_capabilities
# 需要导入模块: from owslib.wms import WebMapService [as 别名]
# 或者: from owslib.wms.WebMapService import getOperationByName [as 别名]
def test_wms_capabilities():
# Fake a request to a WMS Server using saved doc from
# http://wms.jpl.nasa.gov/wms.cgi.
xml = open(resource_file('wms_JPLCapabilities.xml'), 'rb').read()
wms = WebMapService('url', version='1.1.1', xml=xml)
# Test capabilities
# -----------------
assert wms.identification.type == 'OGC:WMS'
assert wms.identification.version == '1.1.1'
assert wms.identification.title == 'JPL Global Imagery Service'
assert wms.identification.abstract == 'WMS Server maintained by JPL, worldwide satellite imagery.'
assert wms.identification.keywords == ['ImageryBaseMapsEarthCover', 'Imagery',
'BaseMaps', 'EarthCover', 'JPL', 'Jet Propulsion Laboratory',
'Landsat', 'WMS', 'SLD', 'Global']
assert wms.identification.accessconstraints == 'Server is load limited'
assert wms.identification.fees == 'none'
assert wms.provider.name == 'JPL'
assert wms.provider.url == 'http://OnEarth.jpl.nasa.gov/index.html'
# Check contact info (some of it is missing)
assert wms.provider.contact.name == 'Lucian Plesea'
assert wms.provider.contact.email == '[email protected]'
wms.provider.contact.address
wms.provider.contact.city
wms.provider.contact.country
wms.provider.contact.region
wms.provider.contact.postcode
assert wms.provider.contact.organization == 'JPL'
wms.provider.contact.position
# Test available content layers
assert isinstance(wms.items(), list) is True
assert isinstance(wms.contents, OrderedDict) is True
# NOTE: Not sure this dictionary interface is right...??
assert sorted(wms.contents.keys()) == ['BMNG', 'daily_afternoon', 'daily_planet',
'gdem', 'global_mosaic', 'global_mosaic_base',
'huemapped_srtm', 'modis', 'srtm_mag', 'srtmplus',
'us_colordem', 'us_elevation', 'us_landsat_wgs84',
'us_ned', 'worldwind_dem']
assert sorted([wms[layer].id for layer in wms.contents]) == ['BMNG', 'daily_afternoon', 'daily_planet',
'gdem', 'global_mosaic', 'global_mosaic_base',
'huemapped_srtm', 'modis', 'srtm_mag', 'srtmplus',
'us_colordem', 'us_elevation', 'us_landsat_wgs84',
'us_ned', 'worldwind_dem']
# Test single item accessor
assert wms['global_mosaic'].title == 'WMS Global Mosaic, pan sharpened'
assert wms['global_mosaic'].keywords == []
['GlobalMosaic', 'Imagery', 'BaseMaps', 'EarthCover', 'JPL', 'Jet Propulsion Laboratory',
'Landsat', 'WMS', 'SLD', 'Global']
wms['global_mosaic'].boundingBox
assert wms['global_mosaic'].boundingBoxWGS84 == (-180.0, -60.0, 180.0, 84.0)
assert sorted(wms['global_mosaic'].crsOptions) == ['AUTO:42003', 'EPSG:4326']
x = wms['global_mosaic'].styles
assert x == {'pseudo_bright': {'title': 'Pseudo-color image (Uses IR and Visual bands, 542 mapping), gamma 1.5'},
'pseudo': {'title': '(default) Pseudo-color image, pan sharpened (Uses IR and Visual bands, 542 mapping), gamma 1.5'}, # noqa
'visual': {'title': 'Real-color image, pan sharpened (Uses the visual bands, 321 mapping), gamma 1.5'},
'pseudo_low': {'title': 'Pseudo-color image, pan sharpened (Uses IR and Visual bands, 542 mapping)'},
'visual_low': {'title': 'Real-color image, pan sharpened (Uses the visual bands, 321 mapping)'},
'visual_bright': {'title': 'Real-color image (Uses the visual bands, 321 mapping), gamma 1.5'}}
# Expecting a KeyError for invalid names
with pytest.raises(KeyError, message="Expecting a KeyError for invalid names"):
wms['utterly bogus'].title
# Test operations
assert sorted([op.name for op in wms.operations]) == ['GetCapabilities', 'GetMap', 'GetTileService']
x = wms.getOperationByName('GetMap').methods
assert x == [{'type': 'Get', 'url': 'http://wms.jpl.nasa.gov/wms.cgi?'}]
assert wms.getOperationByName('GetMap').formatOptions == ['image/jpeg', 'image/png', 'image/geotiff',
'image/tiff', 'application/vnd.google-earth.kml+xml']
# Test exceptions
assert wms.exceptions == ['application/vnd.ogc.se_xml']