mygeocode 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mygeocode/__init__.py +62 -0
- mygeocode/_core.py +286 -0
- mygeocode/_endpoints.py +69 -0
- mygeocode/_version.py +1 -0
- mygeocode/async_client.py +415 -0
- mygeocode/client.py +404 -0
- mygeocode/errors.py +48 -0
- mygeocode/models.py +455 -0
- mygeocode/py.typed +0 -0
- mygeocode-1.1.1.dist-info/METADATA +563 -0
- mygeocode-1.1.1.dist-info/RECORD +13 -0
- mygeocode-1.1.1.dist-info/WHEEL +4 -0
- mygeocode-1.1.1.dist-info/licenses/LICENSE +21 -0
mygeocode/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Official Python client for the My Geocode API: https://www.mygeocode.com/docs/"""
|
|
2
|
+
|
|
3
|
+
from ._core import HttpRequest, HttpResponse
|
|
4
|
+
from ._version import __version__
|
|
5
|
+
from .async_client import AsyncClient
|
|
6
|
+
from .client import Client
|
|
7
|
+
from .errors import ApiError, DecodeError, MyGeocodeError, NetworkError, RequestTimeoutError
|
|
8
|
+
from .models import (
|
|
9
|
+
AutocompleteResponse,
|
|
10
|
+
Bounds,
|
|
11
|
+
Components,
|
|
12
|
+
ElevationPoint,
|
|
13
|
+
ElevationResponse,
|
|
14
|
+
ForwardBatchEntry,
|
|
15
|
+
ForwardBatchResponse,
|
|
16
|
+
ForwardResponse,
|
|
17
|
+
IpBatchResponse,
|
|
18
|
+
IpInfo,
|
|
19
|
+
Meta,
|
|
20
|
+
Place,
|
|
21
|
+
PostcodePlace,
|
|
22
|
+
PostcodeResponse,
|
|
23
|
+
ReverseBatchResponse,
|
|
24
|
+
ReverseResponse,
|
|
25
|
+
Suggestion,
|
|
26
|
+
TimezoneBatchResponse,
|
|
27
|
+
TimezoneInfo,
|
|
28
|
+
TimezoneTransition,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"__version__",
|
|
33
|
+
"Client",
|
|
34
|
+
"AsyncClient",
|
|
35
|
+
"MyGeocodeError",
|
|
36
|
+
"ApiError",
|
|
37
|
+
"RequestTimeoutError",
|
|
38
|
+
"NetworkError",
|
|
39
|
+
"DecodeError",
|
|
40
|
+
"HttpRequest",
|
|
41
|
+
"HttpResponse",
|
|
42
|
+
"Meta",
|
|
43
|
+
"Bounds",
|
|
44
|
+
"Components",
|
|
45
|
+
"Place",
|
|
46
|
+
"ForwardResponse",
|
|
47
|
+
"ForwardBatchEntry",
|
|
48
|
+
"ForwardBatchResponse",
|
|
49
|
+
"ReverseResponse",
|
|
50
|
+
"ReverseBatchResponse",
|
|
51
|
+
"Suggestion",
|
|
52
|
+
"AutocompleteResponse",
|
|
53
|
+
"IpInfo",
|
|
54
|
+
"IpBatchResponse",
|
|
55
|
+
"TimezoneInfo",
|
|
56
|
+
"TimezoneTransition",
|
|
57
|
+
"TimezoneBatchResponse",
|
|
58
|
+
"ElevationPoint",
|
|
59
|
+
"ElevationResponse",
|
|
60
|
+
"PostcodePlace",
|
|
61
|
+
"PostcodeResponse",
|
|
62
|
+
]
|
mygeocode/_core.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Shared by the sync and async clients: options, transport, request building, parameter encoding, parsing, retries.
|
|
2
|
+
|
|
3
|
+
Written for every Python from 3.6: no dataclasses, no ``from __future__`` imports, and annotations that need a newer
|
|
4
|
+
Python are quoted so they are never evaluated.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import socket
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.parse
|
|
14
|
+
import urllib.request
|
|
15
|
+
from collections.abc import Iterable, Mapping
|
|
16
|
+
from http.client import HTTPException
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Optional, Union
|
|
18
|
+
|
|
19
|
+
from ._version import __version__
|
|
20
|
+
from .errors import ApiError, DecodeError, NetworkError, RequestTimeoutError
|
|
21
|
+
from .models import Meta
|
|
22
|
+
|
|
23
|
+
DEFAULT_BASE_URL = "https://api.mygeocode.com/v1"
|
|
24
|
+
USER_AGENT = "mygeocode-python/{} (+https://www.mygeocode.com/sdks/)".format(__version__)
|
|
25
|
+
|
|
26
|
+
# Before 3.10 a socket timeout is socket.timeout, which is not a TimeoutError; from 3.10 it is TimeoutError itself
|
|
27
|
+
# (socket.timeout only remains as an alias there), so the alias is only touched on the versions that need it.
|
|
28
|
+
if sys.version_info >= (3, 10):
|
|
29
|
+
_TIMEOUTS = (TimeoutError,) # type: tuple[type[BaseException], ...]
|
|
30
|
+
else: # pragma: no cover - depends on the running version
|
|
31
|
+
_TIMEOUTS = (TimeoutError, socket.timeout)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Options(object):
|
|
35
|
+
"""The client settings, shared by both clients."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
key: Optional[str],
|
|
40
|
+
base_url: str,
|
|
41
|
+
timeout: float,
|
|
42
|
+
max_retries: int,
|
|
43
|
+
max_retry_wait: float,
|
|
44
|
+
lang: Optional[str],
|
|
45
|
+
clock: "Optional[Callable[[], float]]",
|
|
46
|
+
) -> None:
|
|
47
|
+
if key is None:
|
|
48
|
+
key = os.environ.get("MYGEOCODE_KEY")
|
|
49
|
+
self.key = key.strip() if key and key.strip() else None # type: Optional[str]
|
|
50
|
+
self.base_url = base_url.rstrip("/")
|
|
51
|
+
self.timeout = float(timeout)
|
|
52
|
+
self.max_retries = max(0, int(max_retries))
|
|
53
|
+
self.max_retry_wait = float(max_retry_wait)
|
|
54
|
+
self.lang = lang if lang is not None else "en"
|
|
55
|
+
self.lang_set = lang is not None
|
|
56
|
+
self.clock = clock or time.time # type: Callable[[], float]
|
|
57
|
+
|
|
58
|
+
def headers(self) -> "dict[str, str]":
|
|
59
|
+
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
60
|
+
if self.key:
|
|
61
|
+
headers["X-API-Key"] = self.key
|
|
62
|
+
return headers
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---- transport (standard library only) --------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
if TYPE_CHECKING:
|
|
68
|
+
_HeadersBase = Mapping[str, str]
|
|
69
|
+
else:
|
|
70
|
+
_HeadersBase = Mapping
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Headers(_HeadersBase):
|
|
74
|
+
"""Response headers, read-only, names matched without regard to case."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, items: "Union[Mapping[str, str], Iterable[tuple[str, str]]]" = ()) -> None:
|
|
77
|
+
pairs = items.items() if isinstance(items, Mapping) else items
|
|
78
|
+
self._data = {str(k).lower(): str(v) for k, v in pairs} # type: dict[str, str]
|
|
79
|
+
|
|
80
|
+
def __getitem__(self, name: str) -> str:
|
|
81
|
+
return self._data[name.lower()]
|
|
82
|
+
|
|
83
|
+
def __iter__(self) -> "Iterator[str]":
|
|
84
|
+
return iter(self._data)
|
|
85
|
+
|
|
86
|
+
def __len__(self) -> int:
|
|
87
|
+
return len(self._data)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class HttpRequest(object):
|
|
91
|
+
"""What the client asks a transport to send."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, method: str, url: str, headers: "dict[str, str]", body: Optional[bytes], timeout: float) -> None:
|
|
94
|
+
self.method = method
|
|
95
|
+
self.url = url
|
|
96
|
+
self.headers = headers
|
|
97
|
+
self.body = body
|
|
98
|
+
self.timeout = timeout
|
|
99
|
+
|
|
100
|
+
def __repr__(self) -> str:
|
|
101
|
+
return "HttpRequest({!r}, {!r})".format(self.method, self.url)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class HttpResponse(object):
|
|
105
|
+
"""What a transport returns. Any HTTP status is a response; only a failure to get one raises."""
|
|
106
|
+
|
|
107
|
+
def __init__(self, status: int, headers: "Union[Headers, Mapping[str, str]]", body: bytes) -> None:
|
|
108
|
+
self.status = int(status)
|
|
109
|
+
self.headers = headers if isinstance(headers, Headers) else Headers(headers)
|
|
110
|
+
self.body = body
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def make(cls, status: int, body: bytes = b"", headers: "Optional[Mapping[str, str]]" = None) -> "HttpResponse":
|
|
114
|
+
return cls(status, Headers(headers or {}), body)
|
|
115
|
+
|
|
116
|
+
def __repr__(self) -> str:
|
|
117
|
+
return "HttpResponse({!r})".format(self.status)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def urllib_transport(request: HttpRequest) -> HttpResponse:
|
|
122
|
+
"""The default transport: ``urllib.request`` with the system's certificate store.
|
|
123
|
+
|
|
124
|
+
Raises ``RequestTimeoutError`` or ``NetworkError`` when no answer arrives; any HTTP status is returned.
|
|
125
|
+
"""
|
|
126
|
+
req = urllib.request.Request(request.url, data=request.body, headers=request.headers, method=request.method)
|
|
127
|
+
try:
|
|
128
|
+
with urllib.request.urlopen(req, timeout=request.timeout) as resp:
|
|
129
|
+
return HttpResponse(resp.status, Headers(resp.getheaders()), resp.read())
|
|
130
|
+
except urllib.error.HTTPError as exc:
|
|
131
|
+
try:
|
|
132
|
+
return HttpResponse(exc.code, Headers(exc.headers.items()), exc.read())
|
|
133
|
+
finally:
|
|
134
|
+
exc.close()
|
|
135
|
+
except urllib.error.URLError as exc:
|
|
136
|
+
if isinstance(exc.reason, _TIMEOUTS):
|
|
137
|
+
raise RequestTimeoutError("Request timed out after {} s".format(request.timeout)) from exc
|
|
138
|
+
raise NetworkError("Network error: {}".format(exc.reason)) from exc
|
|
139
|
+
except _TIMEOUTS as exc:
|
|
140
|
+
raise RequestTimeoutError("Request timed out after {} s".format(request.timeout)) from exc
|
|
141
|
+
except (OSError, HTTPException) as exc:
|
|
142
|
+
raise NetworkError("Network error: {}".format(exc)) from exc
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def build_request(opts: Options, method: str, path: str, params: "Mapping[str, str]", body: Any) -> HttpRequest:
|
|
146
|
+
url = "{}/{}".format(opts.base_url, path.lstrip("/"))
|
|
147
|
+
if params:
|
|
148
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
149
|
+
headers = opts.headers()
|
|
150
|
+
data = None # type: Optional[bytes]
|
|
151
|
+
if body is not None:
|
|
152
|
+
data = json.dumps(body, separators=(",", ":")).encode("utf-8")
|
|
153
|
+
headers["Content-Type"] = "application/json"
|
|
154
|
+
return HttpRequest(method, url, headers, data, opts.timeout)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ---- parameter encoding -----------------------------------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _scalar(value: Any) -> str:
|
|
161
|
+
if isinstance(value, bool):
|
|
162
|
+
return "1" if value else "0"
|
|
163
|
+
if isinstance(value, float):
|
|
164
|
+
return repr(value)
|
|
165
|
+
return str(value)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _join(value: Any) -> str:
|
|
169
|
+
if isinstance(value, (list, tuple)):
|
|
170
|
+
return ",".join(_scalar(v) for v in value)
|
|
171
|
+
return _scalar(value)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def encode_params(values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]" = None) -> "dict[str, str]":
|
|
175
|
+
"""Drop ``None`` and ``False``, write ``True`` as ``1``, join lists with commas; ``extra`` is added last and wins."""
|
|
176
|
+
out = {} # type: dict[str, str]
|
|
177
|
+
for name, value in values.items():
|
|
178
|
+
if value is None or value is False:
|
|
179
|
+
continue
|
|
180
|
+
out[name] = _join(value)
|
|
181
|
+
if extra:
|
|
182
|
+
for name, value in extra.items():
|
|
183
|
+
if value is not None:
|
|
184
|
+
out[name] = _join(value)
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def encode_points(points: Any) -> str:
|
|
189
|
+
"""``[(lat, lon), ...]`` to ``lat,lon|lat,lon``; a string (including ``enc:...``) passes through unchanged."""
|
|
190
|
+
if isinstance(points, str):
|
|
191
|
+
return points
|
|
192
|
+
return "|".join("{},{}".format(_scalar(p[0]), _scalar(p[1])) for p in points)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def pairs(points: Any) -> "list[list[float]]":
|
|
196
|
+
return [[p[0], p[1]] for p in points]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---- responses --------------------------------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def parse_response(response: HttpResponse, clock: "Callable[[], float]") -> "tuple[dict[str, Any], Meta]":
|
|
203
|
+
"""The decoded JSON object and its meta, or raise ``ApiError`` / ``DecodeError``."""
|
|
204
|
+
meta = Meta.from_headers(response.headers)
|
|
205
|
+
try:
|
|
206
|
+
data = json.loads(response.body.decode("utf-8"))
|
|
207
|
+
except ValueError: # also UnicodeDecodeError
|
|
208
|
+
data = None
|
|
209
|
+
if response.status >= 400 or (isinstance(data, dict) and data.get("status") == "error"):
|
|
210
|
+
raise _api_error(response, data, meta, clock)
|
|
211
|
+
if not isinstance(data, dict):
|
|
212
|
+
raise DecodeError(
|
|
213
|
+
"Expected a JSON object from the API, got HTTP {} with a body that is not one.".format(response.status)
|
|
214
|
+
)
|
|
215
|
+
return data, meta
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _api_error(response: HttpResponse, data: Any, meta: Meta, clock: "Callable[[], float]") -> ApiError:
|
|
219
|
+
err = {} # type: Mapping[str, Any]
|
|
220
|
+
if isinstance(data, dict) and isinstance(data.get("error"), dict):
|
|
221
|
+
err = data["error"]
|
|
222
|
+
code = str(err.get("code") or "http_error")
|
|
223
|
+
message = str(err.get("message") or "HTTP {}".format(response.status))
|
|
224
|
+
param = err.get("param")
|
|
225
|
+
return ApiError(
|
|
226
|
+
response.status,
|
|
227
|
+
code,
|
|
228
|
+
message,
|
|
229
|
+
param if isinstance(param, str) else None,
|
|
230
|
+
meta.request_id,
|
|
231
|
+
server_wait(response, clock),
|
|
232
|
+
data if isinstance(data, dict) else None,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ---- retries ----------------------------------------------------------------------------------------------------
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def backoff(attempt: int) -> float:
|
|
240
|
+
"""1, 2, 4 ... seconds before the retry that follows failed try number ``attempt`` (counting from 0)."""
|
|
241
|
+
return float(2 ** attempt)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def server_wait(response: HttpResponse, clock: "Callable[[], float]") -> Optional[float]:
|
|
245
|
+
"""Seconds the server asks to wait: ``Retry-After``, or on a 429 the time until ``X-Quota-Reset``."""
|
|
246
|
+
value = _number(response.headers.get("Retry-After"))
|
|
247
|
+
if value is not None:
|
|
248
|
+
return max(0.0, value)
|
|
249
|
+
if response.status == 429:
|
|
250
|
+
reset = _number(response.headers.get("X-Quota-Reset"))
|
|
251
|
+
if reset is not None:
|
|
252
|
+
return max(0.0, reset - clock())
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def retry_wait(opts: Options, response: HttpResponse, attempt: int, retried_500: bool) -> Optional[float]:
|
|
257
|
+
"""Seconds to wait before trying this request again, or ``None`` to raise the error now."""
|
|
258
|
+
if attempt >= opts.max_retries:
|
|
259
|
+
return None
|
|
260
|
+
status = response.status
|
|
261
|
+
if status == 429:
|
|
262
|
+
wait = server_wait(response, opts.clock)
|
|
263
|
+
return wait if wait is not None and wait <= opts.max_retry_wait else None
|
|
264
|
+
if status == 500:
|
|
265
|
+
return None if retried_500 else 1.0
|
|
266
|
+
if status == 503:
|
|
267
|
+
wait = server_wait(response, opts.clock)
|
|
268
|
+
if wait is None:
|
|
269
|
+
wait = backoff(attempt)
|
|
270
|
+
return wait if wait <= opts.max_retry_wait else None
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _number(value: Optional[str]) -> Optional[float]:
|
|
275
|
+
if value is None:
|
|
276
|
+
return None
|
|
277
|
+
try:
|
|
278
|
+
return float(value)
|
|
279
|
+
except ValueError:
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
if TYPE_CHECKING: # names used only in quoted annotations and type comments
|
|
284
|
+
from collections.abc import Callable, Iterator # noqa: F401
|
|
285
|
+
|
|
286
|
+
Transport = Callable[[HttpRequest], HttpResponse]
|
mygeocode/_endpoints.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Request specs for every endpoint. Both clients run them; nothing here touches the network."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Optional
|
|
5
|
+
|
|
6
|
+
from . import models as m
|
|
7
|
+
from ._core import encode_params, encode_points, pairs
|
|
8
|
+
from .models import Meta
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
Parse = Callable[[dict[str, Any], Meta], Any]
|
|
14
|
+
|
|
15
|
+
ANNOTATION_FLAGS = (
|
|
16
|
+
"timezone", "elevation", "wikidata", "country_info", "codes", "sun", "regions", "districts", "census",
|
|
17
|
+
"demographics", "road", "site",
|
|
18
|
+
) # fmt: skip
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Spec(object):
|
|
22
|
+
"""One request: method, path, query parameters, JSON body, and how to read the answer."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self, method: str, path: str, params: "dict[str, str]", body: "Optional[dict[str, Any]]", parse: "Parse"
|
|
26
|
+
) -> None:
|
|
27
|
+
self.method = method
|
|
28
|
+
self.path = path
|
|
29
|
+
self.params = params
|
|
30
|
+
self.body = body
|
|
31
|
+
self.parse = parse
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _model(cls: Any) -> "Parse":
|
|
35
|
+
def parse(data: "dict[str, Any]", meta: Meta) -> Any:
|
|
36
|
+
return cls.from_dict(data, meta)
|
|
37
|
+
|
|
38
|
+
return parse
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _elevation(data: "dict[str, Any]", meta: Meta) -> m.ElevationResponse:
|
|
42
|
+
if "results" not in data and "elevation_m" in data: # a single point answered flat
|
|
43
|
+
data = dict(data, results=[data])
|
|
44
|
+
return m.ElevationResponse.from_dict(data, meta)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get(path: str, values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]", model: Any) -> Spec:
|
|
48
|
+
return Spec("GET", path, encode_params(values, extra), None, _model(model))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def elevation(values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]") -> Spec:
|
|
52
|
+
return Spec("GET", "elevation", encode_params(values, extra), None, _elevation)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def forward_batch(queries: Any, values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]") -> Spec:
|
|
56
|
+
"""POST with only the list in the body; every option goes in the query string."""
|
|
57
|
+
return Spec("POST", "forward", encode_params(values, extra), {"queries": list(queries)}, _model(m.ForwardBatchResponse))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def reverse_batch(points: Any, values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]") -> Spec:
|
|
61
|
+
return Spec("POST", "reverse", encode_params(values, extra), {"coords": pairs(points)}, _model(m.ReverseBatchResponse))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def elevation_batch(points: Any, values: "Mapping[str, Any]", extra: "Optional[Mapping[str, Any]]") -> Spec:
|
|
65
|
+
return Spec("POST", "elevation", encode_params(values, extra), {"locations": pairs(points)}, _elevation)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def points_param(points: Any) -> Optional[str]:
|
|
69
|
+
return None if points is None else encode_points(points)
|
mygeocode/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.1.1"
|