Skip to content
Snippets Groups Projects
wms_srvc_format.py 1.52 KiB
Newer Older
  • Learn to ignore specific revisions
  • Jesper Zedlitz's avatar
    Jesper Zedlitz committed
    import xml.etree.ElementTree as ET
    import requests
    import tempfile
    
    
    def _load_into_file(url):
        response = requests.get(url)
        response.raise_for_status()
    
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(response.content)
            return temp_file
    
    
    
    def _is_capabilites_response(resource, file):
    
    Jesper Zedlitz's avatar
    Jesper Zedlitz committed
        with open(file.name, "rb") as f:
            try:
                xml = ET.parse(f).getroot()
    
    
                if xml.tag == "{http://www.opengis.net/wms}WMS_Capabilities":
                    return True
                else:
                    resource["error"] = (
    
                        "Root element is not {http://www.opengis.net/wms}WMS_Capabilities"
    
                    )
                    return False
            except Exception as e:
                resource["error"] = str(e)
    
    Jesper Zedlitz's avatar
    Jesper Zedlitz committed
                return False
    
    
    def is_valid(resource, file):
    
        if _is_capabilites_response(resource, file):
    
    Jesper Zedlitz's avatar
    Jesper Zedlitz committed
            return True
    
        # The response is not a capabilites XML files. That is allowed.
        # Let's add the request parameters to the URL and try again.
    
        url = resource["url"]
        if "request=" not in url.lower():
            if not url.endswith("?"):
                url = url + "?"
    
            url = url + "service=WMS&request=GetCapabilities"
    
            try:
                return _is_capabilites_response(resource, _load_into_file(url))
            except Exception as e:
                resource["error"] = str(e)
                return False
    
    
    Jesper Zedlitz's avatar
    Jesper Zedlitz committed
        else:
            # The URL already contains a getCapabilites request but the result was not a correct answer.
            return False