forked from geopy/geopy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geocodio.py
240 lines (194 loc) · 8.65 KB
/
geocodio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import json
from functools import partial
from urllib.parse import urlencode
from geopy.exc import GeocoderQueryError, GeocoderQuotaExceeded
from geopy.geocoders.base import DEFAULT_SENTINEL, Geocoder
from geopy.location import Location
from geopy.util import logger
__all__ = ("Geocodio", )
class Geocodio(Geocoder):
"""Geocoder using the Geocod.io API.
Documentation at:
https://www.geocod.io/docs/
Pricing details:
https://www.geocod.io/pricing/
"""
domain = 'api.geocod.io'
geocode_path = '/v1.6/geocode'
reverse_path = '/v1.6/reverse'
def __init__(
self,
api_key,
*,
scheme=None,
timeout=DEFAULT_SENTINEL,
proxies=DEFAULT_SENTINEL,
user_agent=None,
ssl_context=DEFAULT_SENTINEL,
adapter_factory=None
):
"""
:param str api_key:
A valid Geocod.io API key. (https://dash.geocod.io/apikey/create)
:param str scheme:
See :attr:`geopy.geocoders.options.default_scheme`.
:param int timeout:
See :attr:`geopy.geocoders.options.default_timeout`.
:param dict proxies:
See :attr:`geopy.geocoders.options.default_proxies`.
:param str user_agent:
See :attr:`geopy.geocoders.options.default_user_agent`.
:type ssl_context: :class:`ssl.SSLContext`
:param ssl_context:
See :attr:`geopy.geocoders.options.default_ssl_context`.
:param callable adapter_factory:
See :attr:`geopy.geocoders.options.default_adapter_factory`.
"""
super().__init__(
scheme=scheme,
timeout=timeout,
proxies=proxies,
user_agent=user_agent,
ssl_context=ssl_context,
adapter_factory=adapter_factory,
)
self.api_key = api_key
def geocode(
self,
query=None,
*,
limit=None,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
street=None,
city=None,
state=None,
postal_code=None,
country=None
):
"""Return a location point by address. You may either provide a single address
string as a ``query`` argument or individual address components using the
``street``, ``city``, ``state``, ``postal_code``, and ``country`` arguments.
:param str query: The address or query you wish to geocode. You must either
provide this argument or a valid combination of ``street``, ``city``,
``state``, and ``postal_code`` and you may not provide those arguments if
also providing ``query``.
:param int limit: The maximum number of matches to return. This will be reset
to 1 if ``exactly_one`` is ``True``.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param str street: The street address to geocode. If providing this argument
you must provide at least one of ``city``, ``state``, or ``postal_code``, and
you must *not* provide a ``query`` argument.
:param str city: The city of the address to geocode. If providing this argument
you must *not* provide a ``query`` argument.
:param str state: The state of the address to geocode. If providing this argument
you must *not* provide a ``query`` argument.
:param str postal_code: The postal code of the address to geocode. If providing
this argument you must *not* provide a ``query`` argument.
:param str country: The country of the address to geocode. If providing this
argument you must *not* provide a ``query`` argument.
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
if query is not None and \
any(p is not None for p in (city, state, postal_code, country)):
raise GeocoderQueryError('Address component must not be provided if '
'query argument is used.')
if street is not None and \
not any(p is not None for p in (city, state, postal_code)):
raise GeocoderQueryError('If street is provided must also provide city, '
'state, and/or postal_code.')
api = '%s://%s%s' % (self.scheme, self.domain, self.geocode_path)
params = dict(
api_key=self.api_key,
q=query,
street=street,
city=city,
state=state,
postal_code=postal_code,
country=country,
limit=limit
)
params = {
k: v for k, v in params.items() if v is not None
}
url = "?".join((api, urlencode(params)))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
callback = partial(self._parse_json, exactly_one=exactly_one)
return self._call_geocoder(url, callback, timeout=timeout)
def reverse(
self,
query,
*,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
limit=None
):
"""Return an address by location point.
:param str query: The coordinates for which you wish to obtain the
closest human-readable addresses
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:param int limit: The maximum number of matches to return. This will be reset
to 1 if ``exactly_one`` is ``True``.
:rtype: ``None``, :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
params = {
'q': self._coerce_point_to_string(query),
'api_key': self.api_key
}
if limit is not None:
params['limit'] = limit
api = '%s://%s%s' % (self.scheme, self.domain, self.reverse_path)
url = "?".join((api, urlencode(params)))
logger.debug("%s.reverse: %s", self.__class__.__name__, url)
callback = partial(self._parse_json, exactly_one=exactly_one)
return self._call_geocoder(url, callback, timeout=timeout)
def _parse_json(self, page, exactly_one=True):
"""Returns location, (latitude, longitude) from json feed."""
places = page.get('results', [])
def parse_place(place):
"""Get the location, lat, lng from a single json place."""
location = place.get('formatted_address')
latitude = place['location']['lat']
longitude = place['location']['lng']
return Location(location, (latitude, longitude), place)
if exactly_one:
return parse_place(places[0])
else:
return [parse_place(place) for place in places]
def _geocoder_exception_handler(self, error):
"""Custom exception handling for invalid queries and exceeded quotas.
Geocod.io returns a ``422`` status code for invalid queries, which is not mapped
in :const:`~geopy.geocoders.base.ERROR_CODE_MAP`. The service also returns a
``403`` status code for exceeded quotas instead of the ``429`` code mapped in
:const:`~geopy.geocoders.base.ERROR_CODE_MAP`
"""
if error.status_code == 422:
error_message = self._get_error_message(error)
raise GeocoderQueryError(error_message)
if error.status_code == 403:
error_message = self._get_error_message(error)
quota_exceeded_snippet = "You can't make this request as it is " \
"above your daily maximum."
if quota_exceeded_snippet in error_message:
raise GeocoderQuotaExceeded(error_message)
@staticmethod
def _get_error_message(error):
"""Try to extract an error message from the 'error' property of a JSON response.
"""
try:
error_message = json.loads(error.text).get('error')
except json.JSONDecodeError:
error_message = None
return error_message or 'There was an unknown issue with the query.'