Newer
Older
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):
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)
if _is_capabilites_response(resource, file):
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
else:
# The URL already contains a getCapabilites request but the result was not a correct answer.
return False