2 Classes wrapping HTTP responses from the Nominatim API.
4 from collections import OrderedDict
7 import xml.etree.ElementTree as ET
9 from check_functions import Almost
11 def _geojson_result_to_json_result(geojson_result):
12 result = geojson_result['properties']
13 result['geojson'] = geojson_result['geometry']
14 if 'bbox' in geojson_result:
15 # bbox is minlon, minlat, maxlon, maxlat
16 # boundingbox is minlat, maxlat, minlon, maxlon
17 result['boundingbox'] = [geojson_result['bbox'][1],
18 geojson_result['bbox'][3],
19 geojson_result['bbox'][0],
20 geojson_result['bbox'][2]]
23 class BadRowValueAssert:
24 """ Lazily formatted message for failures to find a field content.
27 def __init__(self, response, idx, field, value):
31 self.row = response.result[idx]
34 return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
35 .format(self.idx, self.field, self.value,
36 self.row[self.field], json.dumps(self.row, indent=4))
39 class GenericResponse:
40 """ Common base class for all API responses.
42 def __init__(self, page, fmt, errorcode=200):
49 self.errorcode = errorcode
54 getattr(self, '_parse_' + fmt)()
56 def _parse_json(self):
57 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
62 self.header['json_func'] = m.group(1)
63 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
64 if isinstance(self.result, OrderedDict):
65 self.result = [self.result]
67 def _parse_geojson(self):
69 if 'error' in self.result[0]:
72 self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
74 def _parse_geocodejson(self):
76 if self.result is not None:
77 self.result = [r['geocoding'] for r in self.result]
79 def assert_field(self, idx, field, value):
80 """ Check that result row `idx` has a field `field` with value `value`.
81 Float numbers are matched approximately. When the expected value
82 starts with a carat, regular expression matching is used.
84 assert field in self.result[idx], \
85 "Result row {} has no field '{}'.\nFull row: {}"\
86 .format(idx, field, json.dumps(self.result[idx], indent=4))
88 if isinstance(value, float):
89 assert Almost(value) == float(self.result[idx][field]), \
90 BadRowValueAssert(self, idx, field, value)
91 elif value.startswith("^"):
92 assert re.fullmatch(value, self.result[idx][field]), \
93 BadRowValueAssert(self, idx, field, value)
95 assert str(self.result[idx][field]) == str(value), \
96 BadRowValueAssert(self, idx, field, value)
98 def match_row(self, row):
99 """ Match the result fields against the given behave table row.
101 if 'ID' in row.headings:
102 todo = [int(row['ID'])]
104 todo = range(len(self.result))
107 for name, value in zip(row.headings, row.cells):
111 self.assert_field(i, 'osm_type', value[0])
112 self.assert_field(i, 'osm_id', value[1:])
113 elif name == 'centroid':
114 lon, lat = value.split(' ')
115 self.assert_field(i, 'lat', float(lat))
116 self.assert_field(i, 'lon', float(lon))
118 self.assert_field(i, name, value)
120 def property_list(self, prop):
121 return [x[prop] for x in self.result]
124 class SearchResponse(GenericResponse):
125 """ Specialised class for search and lookup responses.
126 Transforms the xml response in a format similar to json.
129 def _parse_xml(self):
130 xml_tree = ET.fromstring(self.page)
132 self.header = dict(xml_tree.attrib)
134 for child in xml_tree:
135 assert child.tag == "place"
136 self.result.append(dict(child.attrib))
140 if sub.tag == 'extratags':
141 self.result[-1]['extratags'] = {}
143 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
144 elif sub.tag == 'namedetails':
145 self.result[-1]['namedetails'] = {}
147 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
148 elif sub.tag == 'geokml':
149 self.result[-1][sub.tag] = True
151 address[sub.tag] = sub.text
154 self.result[-1]['address'] = address
157 class ReverseResponse(GenericResponse):
158 """ Specialised class for reverse responses.
159 Transforms the xml response in a format similar to json.
162 def _parse_xml(self):
163 xml_tree = ET.fromstring(self.page)
165 self.header = dict(xml_tree.attrib)
168 for child in xml_tree:
169 if child.tag == 'result':
170 assert not self.result, "More than one result in reverse result"
171 self.result.append(dict(child.attrib))
172 elif child.tag == 'addressparts':
175 address[sub.tag] = sub.text
176 self.result[0]['address'] = address
177 elif child.tag == 'extratags':
178 self.result[0]['extratags'] = {}
180 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
181 elif child.tag == 'namedetails':
182 self.result[0]['namedetails'] = {}
184 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
185 elif child.tag == 'geokml':
186 self.result[0][child.tag] = True
188 assert child.tag == 'error', \
189 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
192 class StatusResponse(GenericResponse):
193 """ Specialised class for status responses.
194 Can also parse text responses.
197 def _parse_text(self):