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 OSM_TYPE = {'N' : 'node', 'W' : 'way', 'R' : 'relation'}
13 def _geojson_result_to_json_result(geojson_result):
14 result = geojson_result['properties']
15 result['geojson'] = geojson_result['geometry']
16 if 'bbox' in geojson_result:
17 # bbox is minlon, minlat, maxlon, maxlat
18 # boundingbox is minlat, maxlat, minlon, maxlon
19 result['boundingbox'] = [geojson_result['bbox'][1],
20 geojson_result['bbox'][3],
21 geojson_result['bbox'][0],
22 geojson_result['bbox'][2]]
25 class BadRowValueAssert:
26 """ Lazily formatted message for failures to find a field content.
29 def __init__(self, response, idx, field, value):
33 self.row = response.result[idx]
36 return "\nBad value for row {} field '{}'. Expected: {}, got: {}.\nFull row: {}"""\
37 .format(self.idx, self.field, self.value,
38 self.row[self.field], json.dumps(self.row, indent=4))
41 class GenericResponse:
42 """ Common base class for all API responses.
44 def __init__(self, page, fmt, errorcode=200):
51 self.errorcode = errorcode
55 if errorcode == 200 and fmt != 'debug':
56 getattr(self, '_parse_' + fmt)()
58 def _parse_json(self):
59 m = re.fullmatch(r'([\w$][^(]*)\((.*)\)', self.page)
64 self.header['json_func'] = m.group(1)
65 self.result = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(code)
66 if isinstance(self.result, OrderedDict):
67 self.result = [self.result]
69 def _parse_geojson(self):
71 if 'error' in self.result[0]:
74 self.result = list(map(_geojson_result_to_json_result, self.result[0]['features']))
76 def _parse_geocodejson(self):
78 if self.result is not None:
79 self.result = [r['geocoding'] for r in self.result]
81 def assert_field(self, idx, field, value):
82 """ Check that result row `idx` has a field `field` with value `value`.
83 Float numbers are matched approximately. When the expected value
84 starts with a carat, regular expression matching is used.
86 assert field in self.result[idx], \
87 "Result row {} has no field '{}'.\nFull row: {}"\
88 .format(idx, field, json.dumps(self.result[idx], indent=4))
90 if isinstance(value, float):
91 assert Almost(value) == float(self.result[idx][field]), \
92 BadRowValueAssert(self, idx, field, value)
93 elif value.startswith("^"):
94 assert re.fullmatch(value, self.result[idx][field]), \
95 BadRowValueAssert(self, idx, field, value)
97 assert str(self.result[idx][field]) == str(value), \
98 BadRowValueAssert(self, idx, field, value)
100 def assert_address_field(self, idx, field, value):
101 """ Check that result rows`idx` has a field `field` with value `value`
102 in its address. If idx is None, then all results are checked.
105 todo = range(len(self.result))
110 assert 'address' in self.result[idx], \
111 "Result row {} has no field 'address'.\nFull row: {}"\
112 .format(idx, json.dumps(self.result[idx], indent=4))
114 address = self.result[idx]['address']
115 assert field in address, \
116 "Result row {} has no field '{}' in address.\nFull address: {}"\
117 .format(idx, field, json.dumps(address, indent=4))
119 assert address[field] == value, \
120 "\nBad value for row {} field '{}' in address. Expected: {}, got: {}.\nFull address: {}"""\
121 .format(idx, field, value, address[field], json.dumps(address, indent=4))
123 def match_row(self, row):
124 """ Match the result fields against the given behave table row.
126 if 'ID' in row.headings:
127 todo = [int(row['ID'])]
129 todo = range(len(self.result))
132 for name, value in zip(row.headings, row.cells):
136 assert 'osm_type' in self.result[i], \
137 "Result row {} has no field 'osm_type'.\nFull row: {}"\
138 .format(i, json.dumps(self.result[i], indent=4))
139 assert self.result[i]['osm_type'] in (OSM_TYPE[value[0]], value[0]), \
140 BadRowValueAssert(self, i, 'osm_type', value)
141 self.assert_field(i, 'osm_id', value[1:])
142 elif name == 'centroid':
143 lon, lat = value.split(' ')
144 self.assert_field(i, 'lat', float(lat))
145 self.assert_field(i, 'lon', float(lon))
147 self.assert_field(i, name, value)
149 def property_list(self, prop):
150 return [x[prop] for x in self.result]
153 class SearchResponse(GenericResponse):
154 """ Specialised class for search and lookup responses.
155 Transforms the xml response in a format similar to json.
158 def _parse_xml(self):
159 xml_tree = ET.fromstring(self.page)
161 self.header = dict(xml_tree.attrib)
163 for child in xml_tree:
164 assert child.tag == "place"
165 self.result.append(dict(child.attrib))
169 if sub.tag == 'extratags':
170 self.result[-1]['extratags'] = {}
172 self.result[-1]['extratags'][tag.attrib['key']] = tag.attrib['value']
173 elif sub.tag == 'namedetails':
174 self.result[-1]['namedetails'] = {}
176 self.result[-1]['namedetails'][tag.attrib['desc']] = tag.text
177 elif sub.tag == 'geokml':
178 self.result[-1][sub.tag] = True
180 address[sub.tag] = sub.text
183 self.result[-1]['address'] = address
186 class ReverseResponse(GenericResponse):
187 """ Specialised class for reverse responses.
188 Transforms the xml response in a format similar to json.
191 def _parse_xml(self):
192 xml_tree = ET.fromstring(self.page)
194 self.header = dict(xml_tree.attrib)
197 for child in xml_tree:
198 if child.tag == 'result':
199 assert not self.result, "More than one result in reverse result"
200 self.result.append(dict(child.attrib))
201 elif child.tag == 'addressparts':
204 address[sub.tag] = sub.text
205 self.result[0]['address'] = address
206 elif child.tag == 'extratags':
207 self.result[0]['extratags'] = {}
209 self.result[0]['extratags'][tag.attrib['key']] = tag.attrib['value']
210 elif child.tag == 'namedetails':
211 self.result[0]['namedetails'] = {}
213 self.result[0]['namedetails'][tag.attrib['desc']] = tag.text
214 elif child.tag == 'geokml':
215 self.result[0][child.tag] = True
217 assert child.tag == 'error', \
218 "Unknown XML tag {} on page: {}".format(child.tag, self.page)
221 class StatusResponse(GenericResponse):
222 """ Specialised class for status responses.
223 Can also parse text responses.
226 def _parse_text(self):