示例#1
0
def add_to_axes(ax,fig,crs_df,params_WMS={},zorder=2):
    """
    """
    from owslib.wms import WebMapService
    import io
    import matplotlib.image as mpimg
    xmin, xmax, ymin, ymax = ax.axis()
    bbox_to_wms=(xmin,ymin,xmax,ymax)
    print(bbox_to_wms)
    #calculando tamaño del axes en pixeles
    bbax=ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    size_px=bbax.width * fig.dpi, bbax.height*fig.dpi
    size_px=tuple([int(round(n)) for n in size_px])
    #print(size_px)
    urlWms=params_WMS["url"]
    srsWms=params_WMS["srs"]
    layersWms=  params_WMS["layers"]
    layers_transparent=  params_WMS["transparent"] if "transparent" in params_WMS else True
    layers_format=  params_WMS["format"] if "format" in params_WMS else "image/png"
    wms=WebMapService(urlWms,version="1.1.1")
    #print(list(wms.contents))
    #print(crs_df.upper(),srsWms)
    if crs_df.upper() != srsWms.upper():
        from pyproj import Proj, transform
        print("reproyectando bounds de wms")
        dfProj = Proj(init=crs_df.lower())
        wmsProj = Proj(init=srsWms.lower())
        xmin_WMS,ymin_WMS=transform(dfProj,wmsProj,xmin,ymin)
        xmax_WMS,ymax_WMS=transform(dfProj,wmsProj,xmax,ymax)
        bbox_to_wms=(xmin_WMS,ymin_WMS,xmax_WMS,ymax_WMS)
    img=wms.getmap(layers=layersWms,srs=srsWms,bbox=bbox_to_wms ,format=layers_format,size=size_px,transparent=layers_transparent)
    i=io.BytesIO(img.read())
    i=mpimg.imread(i,format="png")
    ax.imshow(i,extent=[xmin,xmax,ymin,ymax],zorder=zorder)
    def get_wms_image_size(self, layer_name, srs, min_x, min_y, max_x, max_y):
        """
        Get the size of the png image returned for the current service url
        | set service url | ${WMS_URL} |
        | ${image_size_in_kb} | get wms image size | bathymetry | EPSG:4326 | -112 | 55 | -106 | 71 |
        | ${greater_than_5kb} | ${image_size_in_kb} > 5 |
        | Should Be True | ${greater_than_5kb} |
        returns an integer which is the size of the image in kB

        """
        wms = WebMapService(self._url, version=self._ogc_version)

        img = wms.getmap(layers=[layer_name], srs=srs,
                         bbox=(float(min_x),
                               float(min_y),
                               float(max_x),
                               float(max_y)),
                         size=(300, 300), format='image/png')

        out = open('test.png', 'wb')
        out.write(img.read())
        out.close()

        f = open('test.png', 'rb')
        size = os.path.getsize('test.png') / 1024
        f.close()

        os.remove('test.png')

        return int(math.ceil(size))
    def get_wms_image_size(self,layer_name,srs,min_x,min_y,max_x,max_y):
        """
        Get the size of the png image returned for the current service url
        | set service url | ${WMS_URL} |
	    | ${image_size_in_kb} | get wms image size | bathymetry | EPSG:4326 | -112 | 55 | -106 | 71 |
	    | ${greater_than_5kb} | ${image_size_in_kb} > 5 |
	    | Should Be True | ${greater_than_5kb} |
       
        
        returns an integer which is the size of the image in kB
        
        """
        wms = WebMapService(self._url,version=self._ogc_version)

        img = wms.getmap( layers = [layer_name], srs=srs,
                  bbox=(float(min_x),float(min_y),float(max_x),float(max_y)),size=(300,300),format='image/png')

        out = open('test.png','wb')
        out.write(img.read())
        out.close()

        f = open('test.png','rb')
        size = os.path.getsize('test.png') / 1024
        f.close()

        os.remove('test.png')

        return int(math.ceil(size)) 
示例#4
0
def test_wms_style_looping_getmap(ows_server):
    # Use owslib to confirm that we have a somewhat compliant WMS service
    wms = WebMapService(url=ows_server.url + "/wms",
                        version="1.3.0",
                        timeout=120)

    # Ensure that we have at least some layers available
    contents = list(wms.contents)
    test_layer_name = contents[0]
    test_layer = wms.contents[test_layer_name]

    test_layer_styles = wms.contents[test_layer_name].styles

    bbox = test_layer.boundingBoxWGS84
    layer_bbox = pytest.helpers.enclosed_bbox(bbox)
    layer_time = test_layer.timepositions[len(test_layer.timepositions) //
                                          2].strip()

    for style in test_layer_styles:
        img = wms.getmap(
            layers=[test_layer_name],
            styles=[style],
            srs="EPSG:4326",
            bbox=layer_bbox,
            size=(150, 150),
            format="image/png",
            transparent=True,
            time=layer_time,
        )
        assert img.info()['Content-Type'] == 'image/png'
示例#5
0
    def __init__(self, url, version='1.3.0'):
        self.url = url

        self.wms = WebMapService(url, version=version)
        self.response = None
        self.df = None
        self._time_indexes = {}
示例#6
0
    def capcache_query(self):
        self.capcache_tstamp = datetime.utcnow()
        reader = WMSCapabilitiesReader(self.version, url=self.url,
                                       un=self.username,
                                       pw=self.password,
                                       headers=env.wmsclient.headers)
        self.capcache_xml = etree.tostring(reader.read(self.url))

        service = WebMapService(
            url=self.url, version=self.version,
            username=self.username,
            password=self.password,
            xml=str(self.capcache_xml))

        layers = []
        for lid, layer in service.contents.iteritems():
            layers.append(OrderedDict((
                ('id', lid), ('title', layer.title),
                ('index', map(int, layer.index.split('.'))),
            )))

        layers.sort(key=lambda i: i['index'])

        for l in layers:
            del l['index']

        data = OrderedDict((
            ('formats', service.getOperationByName('GetMap').formatOptions),
            ('layers', layers)))

        self.capcache_json = json.dumps(data, ensure_ascii=False)
示例#7
0
文件: data.py 项目: endarthur/gemgis
    def __init__(self, **kwargs):
        """Loading the Web Map Service
        Kwargs:
            path: alternative file path for Web Map Service
        Returns:
            wms: owslib.map.wms111.WebMapService_1_1_1
         """

        # Load URL of WMS service, if not provided use a default service
        url = kwargs.get('url', 'https://ows.terrestris.de/osm/service?')

        # Setting attributes of the WMS object
        try:
            self.object = WebMapService(url)
        except SSLError:
            print(
                "gemgis: SSL Error, potentially related to missing module - try:\n\n pip install -U openssl \n\n"
            )
            raise

        self.url = url
        self.type = self.object.identification.type
        self.version = self.object.identification.version
        self.title = self.object.identification.title
        self.abstract = self.object.identification.abstract
        self.contents = list(self.object.contents)
        self.operations = self.object.operations
示例#8
0
 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)
示例#9
0
def test_getmap_130_national_map():
    """National Map"""
    # TODO: use flaky tests or fix it: https://pypi.python.org/pypi/pytest-ignore-flaky
    url = SERVICE_URL_NATIONAL_MAP
    wms = WebMapService(url, version='1.3.0')
    rsp = wms.getmap(
        layers=['3'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-176.646, 17.7016, -64.8017, 71.2854),
        size=(500, 300),
        format='image/png',
        transparent=True)
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=3" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "box=-176.646%2C17.7016%2C-64.8017%2C71.2854" in wms.request
    assert "width=500" in wms.request
    assert "height=300" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
示例#10
0
    def validate_wms(self) -> None:
        """Validate input arguments with the WMS service."""
        wms = WebMapService(self.url, version=self.version)

        if not isinstance(self.layers, (str, list)):
            raise InvalidInputType("layers", "str or list")

        layers = [self.layers] if isinstance(self.layers, str) else self.layers
        valid_layers = {
            wms[lyr].name: wms[lyr].title
            for lyr in list(wms.contents)
        }
        if any(lyr not in valid_layers.keys() for lyr in layers):
            raise InvalidInputValue("layers",
                                    (f"{n} for {t}"
                                     for n, t in valid_layers.items()))

        valid_outformats = wms.getOperationByName("GetMap").formatOptions
        if self.outformat not in valid_outformats:
            raise InvalidInputValue("outformat", valid_outformats)

        valid_crss = {
            lyr: [s.lower() for s in wms[lyr].crsOptions]
            for lyr in layers
        }
        if any(self.crs not in valid_crss[lyr] for lyr in layers):
            _valid_crss = (f"{lyr}: {', '.join(cs)}\n"
                           for lyr, cs in valid_crss.items())
            raise InvalidInputValue("CRS", _valid_crss)
示例#11
0
def test_wms_getfeatureinfo_130():
    wms = WebMapService(SERVICE_URL, version='1.3.0')

    res1 = wms.getfeatureinfo(
        layers=['bvv:lkr_ex'], srs='EPSG:31468',
        bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg',
        info_format="text/html", xy=(250, 250))
    html_string1 = res1.read().decode("utf-8")
    assert 'lkr_ex' in html_string1
    assert 'gmd_ex' in html_string1

    res2 = wms.getfeatureinfo(
        layers=['bvv:lkr_ex', 'bvv:gmd_ex'], srs='EPSG:31468',
        bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg',
        info_format="text/html", xy=(250, 250))
    html_string2 = res2.read().decode("utf-8")
    assert 'lkr_ex' in html_string2
    assert 'gmd_ex' in html_string2

    res3 = wms.getfeatureinfo(
        layers=['bvv:lkr_ex', 'bvv:gmd_ex'], srs='EPSG:31468',
        bbox=(4500000, 5500000, 4500500, 5500500), size=(500, 500), format='image/jpeg',
        query_layers=['bvv:lkr_ex'], info_format="text/html", xy=(250, 250))
    html_string3 = res3.read().decode("utf-8")
    assert 'lkr_ex' in html_string3
    assert 'gmd_ex' not in html_string3
示例#12
0
def test_ncwms2():
    """Test with an ncWMS2 server.
    """
    # Note that this does not exercise the bug in https://github.com/geopython/OWSLib/issues/556
    wms = WebMapService(NCWMS2_URL, version='1.3.0')
    rsp = wms.getmap(
        layers=['f33_thredds/min_temp'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-124.17, 46.02, -123.29, 46.38),
        size=(256, 256),
        format='image/png',
        transparent=True,
        mode='32bit',

    )
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=f33_thredds/min_temp" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "width=256" in wms.request
    assert "height=256" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
示例#13
0
def test_ncwms2():
    """Test with an ncWMS2 server.
    """
    # Note that this does not exercise the bug in https://github.com/geopython/OWSLib/issues/556
    wms = WebMapService(NCWMS2_URL, version='1.3.0')
    rsp = wms.getmap(
        layers=['f33_thredds/min_temp'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-124.17, 46.02, -123.29, 46.38),
        size=(256, 256),
        format='image/png',
        transparent=True,
        mode='32bit',

    )
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=f33_thredds/min_temp" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "width=256" in wms.request
    assert "height=256" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
示例#14
0
 def loadLayers(self):
     self.dlg.layersTableWidget.setRowCount(0)
     defaultCrs = 'EPSG:2180'
     try:
         wmsCapabilities = WebMapService(self.curServiceData['url'])
     except AttributeError:
         wmsCapabilities = WebMapService(self.curServiceData['url'],
                                         version='1.3.0')
     except requests.exceptions.ReadTimeout:
         self.iface.messageBar().pushMessage(
             'Baza krajowych usług WMS',
             'Serwer WMS nie odpowiada. Spróbuj ponownie później.',
             level=Qgis.Critical)
         return 1
     except requests.exceptions.SSLError:
         self.iface.messageBar().pushMessage(
             'Baza krajowych usług WMS',
             'Błąd połączenia z serwerem WMS.',
             level=Qgis.Critical)
         return 1
     for nr, layer in enumerate(list(wmsCapabilities.contents)):
         wmsLayer = wmsCapabilities[layer]
         self.dlg.layersTableWidget.insertRow(nr)
         self.dlg.layersTableWidget.setItem(nr, 0,
                                            QTableWidgetItem(str(nr + 1)))
         self.dlg.layersTableWidget.setItem(nr, 1,
                                            QTableWidgetItem(wmsLayer.name))
         self.dlg.layersTableWidget.setItem(
             nr, 2, QTableWidgetItem(wmsLayer.title))
         self.dlg.layersTableWidget.setItem(
             nr, 3, QTableWidgetItem(wmsLayer.abstract))
         self.dlg.layersTableWidget.setItem(
             nr, 4,
             QTableWidgetItem(defaultCrs if defaultCrs in wmsLayer.
                              crsOptions else wmsLayer.crsOptions[0]))
示例#15
0
def test_ows_interfaces_wms():
    wmsxml = open(resource_file('wms_JPLCapabilities.xml'), 'rb').read()
    service = WebMapService('url', version='1.1.1', xml=wmsxml)
    # Check each service instance conforms to OWSLib interface
    service.alias = 'WMS'
    isinstance(service, owslib.map.wms111.WebMapService_1_1_1)
    # URL attribute
    assert service.url == 'url'
    # version attribute
    assert service.version == '1.1.1'
    # Identification object
    assert hasattr(service, 'identification')
    # Check all ServiceIdentification attributes
    assert service.identification.type == 'OGC:WMS'
    for attribute in ['type', 'version', 'title', 'abstract', 'keywords', 'accessconstraints', 'fees']:
        assert hasattr(service.identification, attribute)
    # Check all ServiceProvider attributes
    for attribute in ['name', 'url', 'contact']:
        assert hasattr(service.provider, attribute)
    # Check all operations implement IOperationMetadata
    for op in service.operations:
        for attribute in ['name', 'formatOptions', 'methods']:
            assert hasattr(op, attribute)
    # Check all contents implement IContentMetadata as a dictionary
    isinstance(service.contents, OrderedDict)
    # Check any item (WCS coverage, WMS layer etc) from the contents of each service
    # Check it conforms to IContentMetadata interface
    # get random item from contents dictionary -has to be a nicer way to do this!
    content = service.contents[list(service.contents.keys())[0]]
    for attribute in ['id', 'title', 'boundingBox', 'boundingBoxWGS84', 'crsOptions', 'styles', 'timepositions']:
        assert hasattr(content, attribute)
示例#16
0
 def view(self):
     dataset = self.request.params.get('dataset')
     wms_url = self.request.params.get('wms_url')
     if dataset:
         url = self.request.route_url('wms', _query=[('DATASET', dataset)])
         caps_url = self.request.route_url('wms',
                                           _query=[('DATASET', dataset),
                                                   ('service', 'WMS'),
                                                   ('request',
                                                    'GetCapabilities'),
                                                   ('version', '1.1.1')])
         try:
             response = requests.get(caps_url, verify=False)
             if not response.ok:
                 raise Exception("get caps failed: url=%s", caps_url)
             wms = WebMapService(url, version='1.1.1', xml=response.content)
             map_name = dataset.split('/')[-1]
         except:
             logger.exception("wms connect failed")
             raise Exception("could not connect to wms url %s", caps_url)
     elif wms_url:
         try:
             wms = WebMapService(wms_url)
             map_name = wms_url.split('/')[-1]
         except:
             logger.exception("wms connect failed")
             raise Exception("could not connet to wms url %s", wms_url)
     else:
         wms = None
         map_name = None
     return dict(map_script=map_script.render(wms=wms, dataset=dataset),
                 map_name=map_name)
示例#17
0
def test_getmap_130_national_map():
    """National Map"""
    # TODO: use flaky tests or fix it: https://pypi.python.org/pypi/pytest-ignore-flaky
    url = SERVICE_URL_NATIONAL_MAP
    wms = WebMapService(url, version='1.3.0')
    rsp = wms.getmap(
        layers=['3'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-176.646, 17.7016, -64.8017, 71.2854),
        size=(500, 300),
        format='image/png',
        transparent=True)
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=3" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "box=-176.646%2C17.7016%2C-64.8017%2C71.2854" in wms.request
    assert "width=500" in wms.request
    assert "height=300" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
示例#18
0
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
        }
示例#19
0
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
        }
示例#20
0
    def __init__(self, zoom_level=19):
        self.config = self._read_wms_config()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level
        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService
        self.wms = WebMapService(url=self.config.get(section='WMS', option='Url'),
                                 version=self.config.get(section='WMS', option='Version'))
示例#21
0
 def addLayersFromWms(self):
         """Add new LayerDownloaders from the result of a WMS GetCapabilities
         """
         wmsUrl = self.forgeOwsUrl('wms')
         wms = WebMapService(wmsUrl, version='1.1.1')
         layers = wms.items()
         for l in layers:
                 self.addLayerDownloader(l[1])
         return self.layerDownloaders
示例#22
0
def test_fill_project_template(workspace, publ_type, publication):
    ensure_publication(workspace, publ_type, publication)

    qgs_path = f'{settings.LAYMAN_QGIS_DATA_DIR}/{publication}.qgs'
    wms_url = f'{settings.LAYMAN_QGIS_URL}?MAP={qgs_path}'
    wms_version = '1.3.0'

    layer_info = process_client.get_workspace_publication(publ_type, workspace, publication)
    layer_uuid = layer_info['uuid']

    with pytest.raises(requests.exceptions.HTTPError) as excinfo:
        WebMapService(wms_url, version=wms_version)
    assert excinfo.value.response.status_code == 500

    with app.app_context():
        layer_bbox = layer_db.get_bbox(workspace, publication)
        layer_crs = layer_db.get_crs(workspace, publication)
    layer_bbox = layer_bbox if not bbox_util.is_empty(layer_bbox) else crs_def.CRSDefinitions[layer_crs].default_bbox
    with app.app_context():
        qml_path = qgis_util.get_original_style_path(workspace, publication)
    parser = ET.XMLParser(remove_blank_text=True)
    qml_xml = ET.parse(qml_path, parser=parser)
    exp_min_scale = data.PUBLICATIONS[(workspace, publ_type, publication)][data.TEST_DATA].get('min_scale')
    if exp_min_scale is not None:
        assert qml_xml.getroot().attrib['minScale'] == exp_min_scale
    with app.app_context():
        db_types = layer_db.get_geometry_types(workspace, publication)
        db_cols = [
            col for col in layer_db.get_all_column_infos(workspace, publication)
            if col.name not in ['wkb_geometry', 'ogc_fid']
        ]
    qml_geometry = qgis_util.get_qml_geometry_from_qml(qml_xml)
    source_type = qgis_util.get_source_type(db_types, qml_geometry)
    with app.app_context():
        layer_qml_str = qgis_util.fill_layer_template(workspace, publication, layer_uuid, layer_bbox, layer_crs, qml_xml, source_type, db_cols)
    layer_qml = ET.fromstring(layer_qml_str.encode('utf-8'), parser=parser)
    if exp_min_scale is not None:
        assert layer_qml.attrib['minScale'] == exp_min_scale
    with app.app_context():
        qgs_str = qgis_util.fill_project_template(workspace, publication, layer_uuid, layer_qml_str, layer_crs, settings.LAYMAN_OUTPUT_SRS_LIST,
                                                  layer_bbox, source_type)
    with open(qgs_path, "w") as qgs_file:
        print(qgs_str, file=qgs_file)

    wmsi = WebMapService(wms_url, version=wms_version)
    assert publication in wmsi.contents
    wms_layer = wmsi.contents[publication]
    exp_output_srs = set(settings.LAYMAN_OUTPUT_SRS_LIST)
    assert exp_output_srs.issubset(set(wms_layer.crsOptions))
    wms_layer_bbox = next((tuple(bbox_crs[:4]) for bbox_crs in wms_layer.crs_list if bbox_crs[4] == layer_crs))
    assert_util.assert_same_bboxes(wms_layer_bbox, layer_bbox, 0.1)

    os.remove(qgs_path)

    with pytest.raises(requests.exceptions.HTTPError) as excinfo:
        WebMapService(wms_url, version=wms_version)
    assert excinfo.value.response.status_code == 500
示例#23
0
 def gui_addgeos(self,website='http://wms.gsfc.nasa.gov/cgi-bin/wms.cgi?project=GEOS.fp.fcst.inst1_2d_hwl_Nx'):
     'GUI handler for adding the figures from WMS support of GEOS'
     from gui import Popup_list
     try:
         from owslib.wms import WebMapService
         from owslib.util import openURL
         from StringIO import StringIO
         from PIL import Image
         self.line.tb.set_message('Loading WMS from :'+website.split('/')[2])
         wms = WebMapService(website)
         cont = list(wms.contents)
     except Exception as ie:
         print ie
         import tkMessageBox
         tkMessageBox.showwarning('Sorry','Loading WMS map file from '+website.split('/')[2]+' servers not working...')
         return
     titles = [wms[c].title for c in cont]
     arr = [x.split('-')[-1]+':  '+y for x,y in zip(cont,titles)]
     i = Popup_list(arr)
     self.line.tb.set_message('Selected WMS map: '+titles[i].split(',')[-1])
     if wms[cont[i]].timepositions:
         times = wms[cont[i]].timepositions
         j = Popup_list(times)
         time_sel = times[j]
     else:
         time_sel = None
     try:
         if not time_sel:
             time_sel = self.line.ex.datestr+'T12:00'
         ylim = self.line.line.axes.get_ylim()
         xlim = self.line.line.axes.get_xlim()
         #img = wms.getdata(layers=[cont[i]],
         #                  bbox=(ylim[0],xlim[0],ylim[1],xlim[1]),
         #                  size=(480,240),
         #                  transparent=True,
         #                  time=time_sel,
         #                  srs='EPSG:4326',
         #                  format='image/png')
         #leg_call = openURL(img.geturl().replace('GetMap','GetLegend'))
         img = wms.getdata(layers=[cont[i],'countries'],
                           bbox=(ylim[0],xlim[0],ylim[1],xlim[1]),
                           size=(480,240),
                           transparent=True,
                           time=time_sel,
                           srs='EPSG:4326',
                           format='image/png')
         geos = Image.open(StringIO(img.read()))
         self.line.addfigure_under(geos,xlim[0],ylim[0],xlim[1],ylim[1])
         #self.line.line.figure.add
         #leg = Image.open(StringIO(leg_call.read()))
         #self.line.addfigure_under(leg,xlim[0],ylim[0],xlim[1],ylim[1],outside=True)
     except:
         import tkMessageBox
         tkMessageBox.showwarning('Sorry','Problem getting the image to load')
         return
示例#24
0
	def generate_preview_image(self, styles=None):
		wms = WebMapService(self.wms.online_resource)
		img = wms.getmap(layers=[self.name],
			srs='EPSG:4326',
			bbox=self.latlon_bbox,
			size=(300,250), # TODO: Calculate optimum size for preview image at this approx size
			format='image/jpeg',
			transparent=True)
		out = open(('%s.jpg' % (self.name)), 'wb')
		out.write(img.read())
		out.close()
示例#25
0
def build_wms_image(bbox):
    url = "%s/wms" % settings.GEOSERVER_BASE_URL
    wms = WebMapService(url, version='1.1.1')
    img = wms.getmap(layers=['haiti'],
                     srs='EPSG:4326',
                     bbox=bbox,
                     size=(1400, 700),
                     bgcolor="#b5d0d0",
                     format='image/jpeg',
                     transparent=True)
    return img
示例#26
0
def test_wms_getmap_130():
    """GetMap 1.3.0"""
    wms = WebMapService(SERVICE_URL, version='1.3.0')
    rsp = wms.getmap(layers=['nexrad_base_reflect'],
                     styles=['default'],
                     srs='EPSG:4326',
                     bbox=(-126, 24, -66, 50),
                     size=(250, 250),
                     format='image/jpeg',
                     transparent=True)
    assert type(rsp) is ResponseWrapper
示例#27
0
    def __init__(self, zoom_level=19):
        self.logger = logging.getLogger(__name__)
        self.current_directory = os.path.dirname(os.path.realpath(__file__))
        self.env = self._read_env()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level

        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService
        self.wms = WebMapService(url=self.env('URL'),
                                 version=self.env('VERSION'))
示例#28
0
def test_wms_getmap_130():
    """GetMap 1.3.0"""
    wms = WebMapService(SERVICE_URL, version='1.3.0')
    rsp = wms.getmap(
        layers=['nexrad_base_reflect'],
        styles=['default'],
        srs='EPSG:4326',
        bbox=(-126, 24, -66, 50),
        size=(250, 250),
        format='image/jpeg',
        transparent=True)
    assert type(rsp) is ResponseWrapper
示例#29
0
def get_wms_version_negotiate(url, timeout=10):
    """
    OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService
    """

    try:
        LOGGER.debug('Trying a WMS 1.3.0 GetCapabilities request')
        return WebMapService(url, version='1.3.0', timeout=timeout)
    except Exception as err:
        LOGGER.warning('WMS 1.3.0 support not found: %s', err)
        LOGGER.debug('Trying a WMS 1.1.1 GetCapabilities request instead')
        return WebMapService(url, version='1.1.1', timeout=timeout)
示例#30
0
def doWms(url):
    wms = WebMapService(url)

    wmsGetMap = next((i for i in wms.getOperationByName('GetMap').methods
                      if i['type'] == 'Get'), None)
    return {
        'type': 'WMS',
        'contents': list(wms.contents),
        'formats': wms.getOperationByName('GetMap').formatOptions,
        'url': wmsGetMap['url'],
        'service': wms
    }
示例#31
0
def get_wmslist():
    wms = WebMapService(
        'http://192.168.1.232:8080/geoserver/BurntLake/gwc/service/wms?',
        version='1.1.1')

    servlist = list(wms.contents)
    class_variable.layers.append(servlist)

    frmt = list(wms.getOperationByName('GetMap').formatOptions)
    class_variable.formats.append(frmt)

    print('Layers:', class_variable.layers)
    print('Formats:', class_variable.formats)
示例#32
0
def catalog_match_checker():
    url = "https://raw.githubusercontent.com/GeoscienceAustralia/dea-config/master/dev/terria/dea.json"
    catalog_json = urllib.request.urlopen(url)
    data = json.loads(catalog_json.read())

    prod_catalog_list = []
    for catalog in data["catalog"]:
        if catalog["name"] == "DEA Production":
            for group in catalog["items"]:
                for item in group["items"]:
                    if "layers" in item:
                        prod_catalog_list.append(item["layers"])
                    else:
                        for i in item["items"]:
                            if "layers" in i:
                                prod_catalog_list.append(i["layers"])

    prod_wms_url = "https://ows.dea.ga.gov.au"
    prod_wms = WebMapService(url=prod_wms_url + "/wms",
                             version="1.3.0",
                             timeout=120)
    prod_wms_layers = list(prod_wms.contents)
    prod_non_released = list(set(prod_wms_layers) - set(prod_catalog_list))

    dev_catalog_list = []
    for catalog in data["catalog"]:
        if catalog["name"] == "DEA Development":
            for group in catalog["items"]:
                for item in group["items"]:
                    if "layers" in item:
                        dev_catalog_list.append(item["layers"])
                    else:
                        for i in item["items"]:
                            if "layers" in i:
                                dev_catalog_list.append(i["layers"])
    dev_wms_url = "https://ows.dev.dea.ga.gov.au"
    dev_wms = WebMapService(url=dev_wms_url + "/wms",
                            version="1.3.0",
                            timeout=120)
    dev_wms_layers = list(dev_wms.contents)
    dev_non_released = list(set(dev_wms_layers) - set(dev_catalog_list))
    return render_template("catalog-comparison.html",
                           data={
                               "dev_non_released": dev_non_released,
                               "prod_non_released": prod_non_released,
                               "prod_wms_layers": prod_wms_layers,
                               "dev_wms_layers": dev_wms_layers,
                               "dev_catalog_list": dev_catalog_list,
                               "prod_catalog_list": prod_catalog_list,
                           })
def get_layer(layer_name):

    wms = WebMapService('http://geoserver.gis.irisnetlab.be/geoserver/wfs', version="1.3")

    kml = wms.getmap(
        layers=[layer_name],
        srs="epsg:4326",
        bbox=wms[layer_name].boundingBox[:-1],
        size=(3000, 3000),
        format='kml', 
        transparent=True
    ).read()

    return kml
 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])
示例#35
0
def test_wms_getmap_111():
    """MESONET GetMap 1.1.1"""
    wms = WebMapService(SERVICE_URL, version='1.1.1')
    assert wms.request == '{}?service=WMS&request=GetCapabilities&version=1.1.1'.format(SERVICE_URL)
    rsp = wms.getmap(
        layers=['nexrad_base_reflect'],
        styles=['default'],
        srs='EPSG:4326',
        bbox=(-126, 24, -66, 50),
        size=(250, 250),
        format='image/jpeg',
        transparent=True)
    import owslib.util
    assert type(rsp) is ResponseWrapper
示例#36
0
def test_wms_getmap_111():
    """MESONET GetMap 1.1.1"""
    wms = WebMapService(SERVICE_URL, version='1.1.1')
    assert wms.request == '{}?service=WMS&request=GetCapabilities&version=1.1.1'.format(
        SERVICE_URL)
    rsp = wms.getmap(layers=['nexrad_base_reflect'],
                     styles=['default'],
                     srs='EPSG:4326',
                     bbox=(-126, 24, -66, 50),
                     size=(250, 250),
                     format='image/jpeg',
                     transparent=True)
    import owslib.util
    assert type(rsp) is ResponseWrapper
示例#37
0
 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])
示例#38
0
def request_image(bbox, size, wms_url, wms_layer, wms_srs, wms_version,
                  wms_format, retries):
    """
    Request an image from a WMS.

    Parameters
    ----------
    bbox : list of float
        The coordinates of the bounding box. [xmin, ymin, xmax, ymax]
    size : list of int
        The size of the image to be requested in pixels. [x, y]
    wms_url : str
        The url of the WMS service to use.
    wms_layer : str
        The layer of the WMS service to use.
    wms_srs : str
        The spatial reference system of the WMS data to request.
    wms_version : str
        The image format of the WMS data to request.
    wms_format : str
        The version number of the WMS service.
    retries : int
        Amount of times to retry retrieving an image from the WMS if it
        fails.

    Returns
    -------
    img : (MxNx3) array
        The RGB values of each pixel
    """
    for i in range(retries):
        try:
            wms = WebMapService(wms_url, version=wms_version)
            wms_img = wms.getmap(layers=[wms_layer],
                                 srs=wms_srs,
                                 bbox=bbox,
                                 size=size,
                                 format=wms_format,
                                 transparent=True)
            break
        except ReadTimeout as e:
            if i != retries - 1:
                print("ReadTimeout, trying again..")
            else:
                raise e

    img = mpimg.imread(BytesIO(wms_img.read()), 0)

    return img
示例#39
0
    def __init__(self, servername):
        self.wms = WebMapService(servername)
        self.layers = self.wms.contents
        #self.epsg = 'EPSG:4326'
        self.epsg = 'EPSG:21781'
        self.datafiles = []
        self.boundingbox = None
        self.resolution = None
        self.nx = 1024
        self.ny = 1024
        self.has_tmp = False

        self.proj = get_projection(self.epsg)

        self.progress = gdal.TermProgress_nocb
示例#40
0
 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)
示例#41
0
def test_wms_getmap_130_service_exception():
    """GetMap 1.3.0 ServiceException for an invalid CRS"""
    wms = WebMapService(SERVICE_URL, version='1.3.0')
    try:
        wms.getmap(
            layers=['nexrad_base_reflect'],
            styles=['default'],
            srs='EPSG:4328',
            bbox=(-126, 24, -66, 50),
            size=(250, 250),
            format='image/jpeg',
            transparent=True)
    except ServiceException as e:
        assert "msWMSLoadGetMapParams(): WMS server error. Invalid CRS given : CRS must be valid for all requested layers." in str(e)  # noqa
    else:
        assert False
示例#42
0
    def retreive_WMS_metadata(typename):
        workspace, layername = decodeTypeName(typename)

        # workspace is hard-coded in the importer
        url = settings.OGC_SERVER['default']['LOCATION'] + workspace + "/"
        url += layername + "/wms?request=GetCapabilities&version=1.1.1"

        get_cap_data = CreateStoryLayerThumbnailTask.request_geoserver_with_credentials(
            url)
        wms = WebMapService(url, xml=get_cap_data)

        # I found that some dataset advertise illegal bounds - fix them up
        xmin = wms[layername].boundingBoxWGS84[0]
        if math.isnan(xmin) or math.isinf(xmin) or xmin < -180:
            xmin = -180

        ymin = wms[layername].boundingBoxWGS84[1]
        if math.isnan(ymin) or math.isinf(ymin) or ymin < -90:
            ymin = -90

        xmax = wms[layername].boundingBoxWGS84[2]
        if math.isnan(xmax) or math.isinf(xmax) or xmax > 180:
            xmax = 180

        ymax = wms[layername].boundingBoxWGS84[3]
        if math.isnan(ymax) or math.isinf(ymax) or ymax > 90:
            ymax = 90

        return [xmin, ymin, xmax, ymax], wms[layername].timepositions
示例#43
0
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)
示例#44
0
def main():
	wms = WebMapService('http://maps.nzoss.org.nz/mapserv?template=openlayers&service=wms&request=getCapabilities', version='1.1.0')

	layer_name = 'default'
	layer = wms[layer_name]
	
	img = wms.getmap(
		layers=[layer_name],
		srs=layer.crsOptions[0],
		bbox=(layer.boundingBox[0], layer.boundingBox[1], layer.boundingBox[2], layer.boundingBox[3]),
		size=(500,400),
		format='image/png',
		transparent=False
		)

	with open('nz_oss_wms.png', 'wb') as out:
		out.write(img.read())
示例#45
0
def run_test_resource(resource_type, url):
    """tests a CSW service and provides run metrics"""

    if resource_type not in RESOURCE_TYPES.keys():
        msg = gettext('Invalid resource type')
        msg2 = '%s: %s' % (msg, resource_type)
        LOGGER.error(msg2)
        raise RuntimeError(msg2)

    title = None
    start_time = datetime.datetime.utcnow()
    message = None

    try:
        if resource_type == 'OGC:WMS':
            ows = WebMapService(url)
        elif resource_type == 'OGC:WFS':
            ows = WebFeatureService(url)
        elif resource_type == 'OGC:WCS':
            ows = WebCoverageService(url)
        elif resource_type == 'OGC:WPS':
            ows = WebProcessingService(url)
        elif resource_type == 'OGC:CSW':
            ows = CatalogueServiceWeb(url)
        elif resource_type == 'OGC:SOS':
            ows = SensorObservationService(url)
        elif resource_type in ['WWW:LINK', 'urn:geoss:waf']:
            ows = urlopen(url)
            if resource_type == 'WWW:LINK':
                import re
                try:
                    title_re = re.compile("<title>(.+?)</title>")
                    title = title_re.search(ows.read()).group(1)
                except:
                    title = url
            elif resource_type == 'urn:geoss:waf':
                title = 'WAF %s %s' % (gettext('for'), urlparse(url).hostname)
        elif resource_type == 'FTP':
            ows = urlopen(url)
            title = urlparse(url).hostname
        success = True
        if resource_type.startswith('OGC:'):
            title = ows.identification.title
        if title is None:
            title = '%s %s %s' % (resource_type, gettext('for'), url)
    except Exception as err:
        msg = str(err)
        LOGGER.exception(msg)
        message = msg
        success = False

    end_time = datetime.datetime.utcnow()

    delta = end_time - start_time
    response_time = '%s.%s' % (delta.seconds, delta.microseconds)

    return [title, success, response_time, message, start_time]
示例#46
0
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
    def __init__(self, zoom_level=19):
        self.logger = logging.getLogger(__name__)
        self.current_directory = os.path.dirname(os.path.realpath(__file__))
        self.env = self._read_env()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level

        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService

        self.wms = WebMapService(url=self.env("URL"), version=self.env("VERSION"))
示例#48
0
def retrieve_map_owslib(uri, bbox, srs, size, image_format, styles, layers, wms=None):
    """Retrieve image of a map from wms server using owslib."""
    
    print 'Use owslib method'
    if not wms:
        # Get the wms object
        wms = WebMapService(uri)

    # This is important to make sure they have the same length
    if len(styles) != len(layers):
        styles = [''] * len(layers)

    image = wms.getmap(
        layers=layers,
        styles=styles,
        srs=srs,
        bbox=bbox,
        size=size,
        format=image_format,
        transparent=True
    )

    return image
示例#49
0
def get_dop(bbox, size):
    from owslib.wms import WebMapService
    wms = WebMapService('http://geodaten.bayern.de/ogc/ogc_dop200_oa.cgi?', version='1.1.1')
    
    img = wms.getmap(
        layers=['adv_dop200c'],
        srs='EPSG:4326', # WGS84
        #srs='EPSG:31468', # GK4
        bbox=bbox,
        size=size,
        format='image/png'
    )
    
    # TODO 
    import cStringIO
    imgIO = cStringIO.StringIO(img.read())
    try:
        img = Image.open(imgIO)
        #img.show()
    except:
        print imgIO.read();   
        raise
    
    return img
示例#50
0
def run_test_resource(resource_type, url):
    """tests a CSW service and provides run metrics"""

    if resource_type not in RESOURCE_TYPES.keys():
        msg = 'Invalid resource type: %s' % resource_type
        LOGGER.error(msg)
        raise RuntimeError(msg)

    title = None
    start_time = datetime.datetime.utcnow()
    message = None

    try:
        if resource_type == 'OGC:WMS':
            ows = WebMapService(url)
        elif resource_type == 'OGC:WFS':
            ows = WebFeatureService(url)
        elif resource_type == 'OGC:WCS':
            ows = WebCoverageService(url)
        elif resource_type == 'OGC:WPS':
            ows = WebProcessingService(url)
        elif resource_type == 'OGC:CSW':
            ows = CatalogueServiceWeb(url)
        elif resource_type == 'OGC:SOS':
            ows = SensorObservationService(url)
        elif resource_type in ['WWW:LINK', 'urn:geoss:waf']:
            ows = urlopen(url)
            if resource_type == 'WWW:LINK':
                import re
                try:
                    title_re = re.compile("<title>(.+?)</title>")
                    title = title_re.search(ows.read()).group(1)
                except:
                    title = url
            elif resource_type == 'urn:geoss:waf':
                title = 'WAF for %s' % urlparse(url).hostname
        elif resource_type == 'FTP':
            ows = urlopen(url)
            title = urlparse(url).hostname
        success = True
        if resource_type.startswith('OGC:'):
            title = ows.identification.title
        if title is None:
            title = '%s for %s' % (resource_type, url)
    except Exception, err:
        msg = str(err)
        LOGGER.exception(msg)
        message = msg
        success = False
class WmsApi:
    def __init__(self, zoom_level=19):
        self.logger = logging.getLogger(__name__)
        self.current_directory = os.path.dirname(os.path.realpath(__file__))
        self.env = self._read_env()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level

        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService

        self.wms = WebMapService(url=self.env("URL"), version=self.env("VERSION"))

    def set_auth(self):
        user = self.env("NTLM_USER")
        password = self.env("NTLM_PASSWORD")
        return HttpNtlmAuth(user, password) if user is not None and password is not None else None

    def _read_env(self):
        env = environ.Env(
            NTLM_USER=(str, None),
            NTLM_PASSWORD=(str, None),
            URL=(str, None),
            SRS=(str, None),
            VERSION=(str, None),
            LAYER=(str, None),
        )
        current = environ.Path(self.current_directory)
        environ.Env.read_env(current(".env"))
        self._settings_check(env)
        return env

    def _settings_check(self, env):
        if env("URL") is None or env("SRS") is None or env("VERSION") is None or env("LAYER") is None:
            error_message = "You have to set all URL, SRS, LAYER and VERSION in your .env config file."
            self.logger.error(error_message)
            raise Exception(error_message)

    @staticmethod
    def _auth_monkey_patch(auth):
        AuthMonkeyPatch(auth)

    def get_image(self, bbox):
        size = self._calculate_image_size(bbox, self.zoom_level)
        image = self._get(
            layers=[self.env("LAYER")], srs=self.env("SRS"), bbox=self._box(bbox), size=size, format="image/jpeg"
        )
        return image

    @staticmethod
    def _calculate_image_size(bbox, zoom_level):
        meters_per_pixel = geo_helper.meters_per_pixel(zoom_level, bbox.bottom)
        width_meter = bbox.node_left_down().get_distance_in_meter(bbox.node_right_down())
        height_meter = bbox.node_left_down().get_distance_in_meter(bbox.node_left_up())
        height = int(height_meter / meters_per_pixel)
        width = int(width_meter / meters_per_pixel)
        return width, height

    def _get(self, **kwargs):
        img = self.wms.getmap(**kwargs)
        return Image.open(BytesIO(img.read()))

    @staticmethod
    def _box(bbox):
        node_left_down = bbox.node_left_down()
        node_right_up = bbox.node_right_up()
        return node_left_down.longitude, node_left_down.latitude, node_right_up.longitude, node_right_up.latitude
示例#52
0
文件: wms.py 项目: iraqez/AgroGis
from owslib.wms import WebMapService
wms = WebMapService('http://212.26.144.110/geowebcache/service/wms', version='1.1.1')

wms.getfeatureinfo(layers='kadastr', query_layers='kadastr',styles='',
                   info_format='application/vnd.ogc.gml',srs='EPSG:900913')
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
            }
示例#54
0
文件: metadata.py 项目: iwillig/pycsw
def _parse_wms(context, repos, record, identifier):

    from owslib.wms import WebMapService

    recobjs = []
    serviceobj = repos.dataset()

    md = WebMapService(record)

    # generate record of service instance
    _set(context, serviceobj, 'pycsw:Identifier', identifier)
    _set(context, serviceobj, 'pycsw:Typename', 'csw:Record')
    _set(context, serviceobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
    _set(context, serviceobj, 'pycsw:MdSource', record)
    _set(context, serviceobj, 'pycsw:InsertDate', util.get_today_and_now())
    _set(context, serviceobj, 'pycsw:XML', md.getServiceXML())
    _set(context, serviceobj, 'pycsw:AnyText', util.get_anytext(md.getServiceXML()))
    _set(context, serviceobj, 'pycsw:Type', 'service')
    _set(context, serviceobj, 'pycsw:Title', md.identification.title)
    _set(context, serviceobj, 'pycsw:Abstract', md.identification.abstract)
    _set(context, serviceobj, 'pycsw:Keywords', ','.join(md.identification.keywords))
    _set(context, serviceobj, 'pycsw:Creator', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Publisher', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Contributor', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:OrganizationName', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:AccessConstraints', md.identification.accessconstraints)
    _set(context, serviceobj, 'pycsw:OtherConstraints', md.identification.fees)
    _set(context, serviceobj, 'pycsw:Source', record)
    _set(context, serviceobj, 'pycsw:Format', md.identification.type)
    for c in md.contents:
        if md.contents[c].parent is None:
            bbox = md.contents[c].boundingBoxWGS84
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, serviceobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            break
    _set(context, serviceobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
    _set(context, serviceobj, 'pycsw:DistanceUOM', 'degrees')
    _set(context, serviceobj, 'pycsw:ServiceType', md.identification.type)
    _set(context, serviceobj, 'pycsw:ServiceTypeVersion', md.identification.version)
    _set(context, serviceobj, 'pycsw:Operation', ','.join([d.name for d in md.operations]))
    _set(context, serviceobj, 'pycsw:OperatesOn', ','.join(list(md.contents)))
    _set(context, serviceobj, 'pycsw:CouplingType', 'tight')

    recobjs.append(serviceobj) 
         
    # generate record foreach layer

    LOGGER.debug('Harvesting %d WMS layers' % len(md.contents))

    for layer in md.contents:
        recobj = repos.dataset()
        identifier2 = '%s-%s' % (identifier, md.contents[layer].name)
        _set(context, recobj, 'pycsw:Identifier', identifier2)
        _set(context, recobj, 'pycsw:Typename', 'csw:Record')
        _set(context, recobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
        _set(context, recobj, 'pycsw:MdSource', record)
        _set(context, recobj, 'pycsw:InsertDate', util.get_today_and_now())
        _set(context, recobj, 'pycsw:XML', md.getServiceXML())
        _set(context, recobj, 'pycsw:AnyText', util.get_anytext(md._capabilities))
        _set(context, recobj, 'pycsw:Type', 'dataset')
        _set(context, recobj, 'pycsw:ParentIdentifier', identifier)
        _set(context, recobj, 'pycsw:Title', md.contents[layer].title)
        _set(context, recobj, 'pycsw:Abstract', md.contents[layer].abstract)
        _set(context, recobj, 'pycsw:Keywords', ','.join(md.contents[layer].keywords))

        bbox = md.contents[layer].boundingBoxWGS84
        if bbox is not None:
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
            _set(context, recobj, 'pycsw:Denominator', 'degrees')
        else:
            bbox = md.contents[layer].boundingBox
            if bbox:
                tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
                _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
                _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:%s' % \
                bbox[-1].split(':')[1])

        recobjs.append(recobj)

    return recobjs
示例#55
0
文件: metadata.py 项目: simod/pycsw
def _parse_wms(context, repos, record, identifier):

    from owslib.wms import WebMapService

    recobjs = []
    serviceobj = repos.dataset()

    md = WebMapService(record)

    # generate record of service instance
    _set(context, serviceobj, 'pycsw:Identifier', identifier)
    _set(context, serviceobj, 'pycsw:Typename', 'csw:Record')
    _set(context, serviceobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
    _set(context, serviceobj, 'pycsw:MdSource', record)
    _set(context, serviceobj, 'pycsw:InsertDate', util.get_today_and_now())
    _set(context, serviceobj, 'pycsw:XML', md.getServiceXML())
    _set(context, serviceobj, 'pycsw:AnyText', util.get_anytext(md.getServiceXML()))
    _set(context, serviceobj, 'pycsw:Type', 'service')
    _set(context, serviceobj, 'pycsw:Title', md.identification.title)
    _set(context, serviceobj, 'pycsw:Abstract', md.identification.abstract)
    _set(context, serviceobj, 'pycsw:Keywords', ','.join(md.identification.keywords))
    _set(context, serviceobj, 'pycsw:Creator', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Publisher', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Contributor', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:OrganizationName', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:AccessConstraints', md.identification.accessconstraints)
    _set(context, serviceobj, 'pycsw:OtherConstraints', md.identification.fees)
    _set(context, serviceobj, 'pycsw:Source', record)
    _set(context, serviceobj, 'pycsw:Format', md.identification.type)
    for c in md.contents:
        if md.contents[c].parent is None:
            bbox = md.contents[c].boundingBoxWGS84
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, serviceobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            break
    _set(context, serviceobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
    _set(context, serviceobj, 'pycsw:DistanceUOM', 'degrees')
    _set(context, serviceobj, 'pycsw:ServiceType', md.identification.type)
    _set(context, serviceobj, 'pycsw:ServiceTypeVersion', md.identification.version)
    _set(context, serviceobj, 'pycsw:Operation', ','.join([d.name for d in md.operations]))
    _set(context, serviceobj, 'pycsw:OperatesOn', ','.join(list(md.contents)))
    _set(context, serviceobj, 'pycsw:CouplingType', 'tight')

    links = [
        '%s,OGC-WMS Web Map Service,OGC:WMS,%s' % (identifier, md.url),
        '%s,OGC-WMS Capabilities service (ver 1.1.1),OGC:WMS-1.1.1-http-get-capabilities,%s' % (identifier, build_get_url(md.url, {'service': 'WMS', 'version': '1.1.1', 'request': 'GetCapabilities'})),
    ]

    _set(context, serviceobj, 'pycsw:Links', '^'.join(links))

    recobjs.append(serviceobj) 
         
    # generate record foreach layer

    LOGGER.debug('Harvesting %d WMS layers' % len(md.contents))

    for layer in md.contents:
        recobj = repos.dataset()
        identifier2 = '%s-%s' % (identifier, md.contents[layer].name)
        _set(context, recobj, 'pycsw:Identifier', identifier2)
        _set(context, recobj, 'pycsw:Typename', 'csw:Record')
        _set(context, recobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
        _set(context, recobj, 'pycsw:MdSource', record)
        _set(context, recobj, 'pycsw:InsertDate', util.get_today_and_now())
        _set(context, recobj, 'pycsw:XML', md.getServiceXML())
        _set(context, recobj, 'pycsw:AnyText', util.get_anytext(md._capabilities))
        _set(context, recobj, 'pycsw:Type', 'dataset')
        _set(context, recobj, 'pycsw:ParentIdentifier', identifier)
        _set(context, recobj, 'pycsw:Title', md.contents[layer].title)
        _set(context, recobj, 'pycsw:Abstract', md.contents[layer].abstract)
        _set(context, recobj, 'pycsw:Keywords', ','.join(md.contents[layer].keywords))

        bbox = md.contents[layer].boundingBoxWGS84
        if bbox is not None:
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
            _set(context, recobj, 'pycsw:Denominator', 'degrees')
        else:
            bbox = md.contents[layer].boundingBox
            if bbox:
                tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
                _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
                _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:%s' % \
                bbox[-1].split(':')[1])

        params = {
            'service': 'WMS',
            'version': '1.1.1',
            'request': 'GetMap',
            'layers': md.contents[layer].name,
            'format': 'image/png',
            'height': '200',
            'width': '200',
            'srs': 'EPSG:4326',
            'bbox':  '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3]),
            'styles': ''
        }

        links = [
            '%s,Web image thumbnail (URL),WWW:LINK-1.0-http--image-thumbnail,%s' % (md.contents[layer].name, build_get_url(md.url, params))
        ]

        _set(context, recobj, 'pycsw:Links', '^'.join(links))

        recobjs.append(recobj)

    return recobjs
示例#56
0
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
示例#57
0
        <LayerSRS>WGS84</LayerSRS>
        <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>
    </OGRVRTLayer>
</OGRVRTDataSource>
        '''
    fname = iname.strip().split('.')[0]
    oname = fname+".vrt"
    output = template % (fname,iname,lon,lat)
    # opens an text file to write the output to
    outFileHandle = open(oname, "w")
    outFileHandle.write(output)
    outFileHandle.close()

if __name__ == '__main__':

    wms = WebMapService('http://bhuvan5.nrsc.gov.in/bhuvan/wms')
    '''
    # learn on WMS services  
    print(wms.identification.type)
    print(wms.identification.version)
    print(wms.identification.title)
    print(wms.identification.abstract)
    print(list(wms.contents))
    print(wms['vector:AS_LULC50K_1112'].title)
    print(wms['vector:AS_LULC50K_1112'].boundingBoxWGS84)
    print(wms['vector:AS_LULC50K_1112'].crsOptions)
    print(wms['vector:AS_LULC50K_1112'].styles)
    '''
    # download WMS image for the study area
    # consider spliting large area - high resolution/large data may end with download failure
    pixsize = 0.0002  # put the desired resolution (in the SRS unit), 0.0002 deg = approx. 20m