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()
xml.tag == "{http://www.opengis.net/wfs/2.0}WFS_Capabilities"
or xml.tag == "{http://www.opengis.net/wfs}WFS_Capabilities"
):
return True
else:
resource["error"] = "Root element is not WFS_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=WFS&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