Skip to content

Commit 7a9edb3

Browse files
author
nilsnolde
committed
Merge branch 'master' into development
2 parents b1dc2e3 + 3060a29 commit 7a9edb3

25 files changed

+1183
-1006
lines changed

docs/source/conf.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
#
1919
import os
2020
import sys
21-
#sys.path.insert(0, 'C:\\Users\\gisadmin\\Documents\\Dev\\Git\\Uni\\ORS\\infrastructure\\SDK\\openrouteservice-python-api\\openrouteservice')
21+
22+
# sys.path.insert(0, 'C:\\Users\\gisadmin\\Documents\\Dev\\Git\\Uni\\ORS\\infrastructure\\SDK\\openrouteservice-python-api\\openrouteservice')
2223
sys.path.insert(0, os.path.abspath('../..'))
2324

2425
# -- General configuration ------------------------------------------------
@@ -30,9 +31,11 @@
3031
# Add any Sphinx extension module names here, as strings. They can be
3132
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
3233
# ones.
33-
extensions = ['sphinx.ext.autodoc',
34+
extensions = [
35+
'sphinx.ext.autodoc',
3436
'sphinx.ext.todo',
35-
'sphinx.ext.coverage']
37+
'sphinx.ext.coverage'
38+
]
3639

3740
# Add any paths that contain templates here, relative to this directory.
3841
templates_path = ['.templates']
@@ -78,7 +81,6 @@
7881
# If true, `todo` and `todoList` produce output, else they produce nothing.
7982
todo_include_todos = True
8083

81-
8284
# -- Options for HTML output ----------------------------------------------
8385

8486
# The theme to use for HTML and HTML Help pages. See the documentation for
@@ -112,13 +114,11 @@
112114
]
113115
}
114116

115-
116117
# -- Options for HTMLHelp output ------------------------------------------
117118

118119
# Output file base name for HTML help builder.
119120
htmlhelp_basename = 'openrouteservice-pydoc'
120121

121-
122122
# -- Options for LaTeX output ---------------------------------------------
123123

124124
latex_elements = {
@@ -147,7 +147,6 @@
147147
u'Nils Nolde', 'manual'),
148148
]
149149

150-
151150
# -- Options for manual page output ---------------------------------------
152151

153152
# One entry per manual page. List of tuples
@@ -157,7 +156,6 @@
157156
[author], 1)
158157
]
159158

160-
161159
# -- Options for Texinfo output -------------------------------------------
162160

163161
# Grouping the document tree into Texinfo files. List of tuples
@@ -168,6 +166,3 @@
168166
author, 'openrouteservice-py', 'One line description of project.',
169167
'Miscellaneous'),
170168
]
171-
172-
173-

openrouteservice/__init__.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,23 @@
1919

2020
__version__ = "2.0.0"
2121

22+
2223
# Make sure QGIS plugin can import openrouteservice-py
2324

25+
26+
def get_ordinal(number):
27+
"""Produces an ordinal (1st, 2nd, 3rd, 4th) from a number"""
28+
29+
if number == 1:
30+
return 'st'
31+
elif number == 2:
32+
return 'nd'
33+
elif number == 3:
34+
return 'rd'
35+
else:
36+
return 'th'
37+
38+
2439
from openrouteservice.client import Client
2540
## Allow sphinx to pick up these symbols for the documentation.
26-
#__all__ = ["Client"]
41+
# __all__ = ["Client"]

openrouteservice/client.py

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,27 +30,27 @@
3030
import time
3131
import warnings
3232

33-
from openrouteservice import exceptions, __version__
33+
from openrouteservice import exceptions, __version__, get_ordinal
3434

35-
try: # Python 3
35+
try: # Python 3
3636
from urllib.parse import urlencode
37-
except ImportError: # Python 2
37+
except ImportError: # Python 2
3838
from urllib import urlencode
3939

40-
4140
_USER_AGENT = "ORSClientPython.v{}".format(__version__)
4241
_DEFAULT_BASE_URL = "https://api.openrouteservice.org"
4342

4443
_RETRIABLE_STATUSES = set([503])
4544

45+
4646
class Client(object):
4747
"""Performs requests to the ORS API services."""
4848

4949
def __init__(self,
5050
key=None,
5151
base_url=_DEFAULT_BASE_URL,
5252
timeout=60,
53-
retry_timeout=60,
53+
retry_timeout=60,
5454
requests_kwargs=None,
5555
retry_over_query_limit=True):
5656
"""
@@ -91,16 +91,19 @@ def __init__(self,
9191
self._base_url = base_url
9292

9393
if self._base_url == _DEFAULT_BASE_URL and key is None:
94-
raise ValueError("No API key was specified. Please visit https://openrouteservice.org/sign-up to create one.")
94+
raise ValueError(
95+
"No API key was specified. Please visit https://openrouteservice.org/sign-up to create one.")
9596

9697
self._timeout = timeout
9798
self._retry_over_query_limit = retry_over_query_limit
9899
self._retry_timeout = timedelta(seconds=retry_timeout)
99100
self._requests_kwargs = requests_kwargs or {}
100101
self._requests_kwargs.update({
101-
"headers": {"User-Agent": _USER_AGENT,
102-
'Content-type': 'application/json',
103-
"Authorization": self._key},
102+
"headers": {
103+
"User-Agent": _USER_AGENT,
104+
'Content-type': 'application/json',
105+
"Authorization": self._key
106+
},
104107
"timeout": self._timeout,
105108
})
106109

@@ -171,20 +174,20 @@ def request(self,
171174
# requests_kwargs arg overriding.
172175
requests_kwargs = requests_kwargs or {}
173176
final_requests_kwargs = dict(self._requests_kwargs, **requests_kwargs)
174-
177+
175178
# Determine GET/POST.
176179
requests_method = self._session.get
177-
180+
178181
if post_json is not None:
179182
requests_method = self._session.post
180183
final_requests_kwargs["json"] = post_json
181-
184+
182185
# Only print URL and parameters for dry_run
183186
if dry_run:
184187
print("url:\n{}\nHeaders:\n{}".format(self._base_url + authed_url,
185188
json.dumps(final_requests_kwargs, indent=2)))
186189
return
187-
190+
188191
try:
189192
response = requests_method(self._base_url + authed_url,
190193
**final_requests_kwargs)
@@ -195,10 +198,11 @@ def request(self,
195198

196199
if response.status_code in _RETRIABLE_STATUSES:
197200
# Retry request.
198-
warnings.warn('Server down.\nRetrying for the {}th time.'.format(retry_counter + 1),
201+
warnings.warn('Server down.\nRetrying for the {0}{1} time.'.format(retry_counter + 1,
202+
get_ordinal(retry_counter + 1)),
199203
UserWarning,
200204
stacklevel=1)
201-
205+
202206
return self.request(url, get_params, first_request_time,
203207
retry_counter + 1, requests_kwargs, post_json)
204208

@@ -209,8 +213,9 @@ def request(self,
209213
except exceptions._RetriableRequest as e:
210214
if isinstance(e, exceptions._OverQueryLimit) and not self._retry_over_query_limit:
211215
raise
212-
213-
warnings.warn('Rate limit exceeded.\nRetrying for the {}th time.'.format(retry_counter + 1),
216+
217+
warnings.warn('Rate limit exceeded. Retrying for the {0}{1} time.'.format(retry_counter + 1,
218+
get_ordinal(retry_counter + 1)),
214219
UserWarning,
215220
stacklevel=1)
216221
# Retry request.
@@ -223,11 +228,13 @@ def req(self):
223228
"""Returns request object. Can be used in case of request failure."""
224229
return self._req
225230

226-
def _get_body(self, response):
231+
@staticmethod
232+
def _get_body(response):
233+
"""Returns the body of a response object, raises status code exceptions if necessary."""
227234
body = response.json()
228-
# error = body.get('error')
235+
# error = body.get('error')
229236
status_code = response.status_code
230-
237+
231238
if status_code == 429:
232239
raise exceptions._OverQueryLimit(
233240
status_code,
@@ -241,7 +248,8 @@ def _get_body(self, response):
241248

242249
return body
243250

244-
def _generate_auth_url(self, path, params):
251+
@staticmethod
252+
def _generate_auth_url(path, params):
245253
"""Returns the path and query string portion of the request URL, first
246254
adding any necessary parameters.
247255
@@ -254,10 +262,10 @@ def _generate_auth_url(self, path, params):
254262
:rtype: string
255263
256264
"""
257-
265+
258266
if type(params) is dict:
259267
params = sorted(dict(**params).items())
260-
268+
261269
return path + "?" + _urlencode_params(params)
262270

263271

@@ -283,6 +291,7 @@ def _make_api_method(func):
283291
Please note that this is an unsupported feature for advanced use only.
284292
It's also currently incompatibile with multiple threads, see GH #160.
285293
"""
294+
286295
@functools.wraps(func)
287296
def wrapper(*args, **kwargs):
288297
args[0]._extra_params = kwargs.pop("extra_params", None)
@@ -292,6 +301,7 @@ def wrapper(*args, **kwargs):
292301
except AttributeError:
293302
pass
294303
return result
304+
295305
return wrapper
296306

297307

openrouteservice/convert.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,14 @@
2020
"""Converts Python types to string representations suitable for ORS API server.
2121
"""
2222

23+
2324
def _pipe_list(arg):
2425
"""Convert list of values to pipe-delimited string"""
2526
if not _is_list(arg):
2627
raise TypeError(
2728
"Expected a list or tuple, "
2829
"but got {}".format(type(arg).__name__))
29-
return "|".join(map(str,arg))
30+
return "|".join(map(str, arg))
3031

3132

3233
def _comma_list(arg):
@@ -35,12 +36,12 @@ def _comma_list(arg):
3536
raise TypeError(
3637
"Expected a list or tuple, "
3738
"but got {}".format(type(arg).__name__))
38-
return ",".join(map(str,arg))
39+
return ",".join(map(str, arg))
3940

4041

4142
def _convert_bool(boolean):
4243
"""Convert to stringified boolean"""
43-
44+
4445
return str(boolean).lower()
4546

4647

@@ -105,10 +106,10 @@ def _concat_coords(arg):
105106

106107

107108
def _is_list(arg):
108-
"""Checks if arg is list-like."""
109+
"""Checks if arg is list-like."""
109110
if isinstance(arg, dict):
110111
return False
111-
if isinstance(arg, str): # Python 3-only, as str has __iter__
112+
if isinstance(arg, str): # Python 3-only, as str has __iter__
112113
return False
113114
return (not _has_method(arg, "strip")
114115
and _has_method(arg, "__getitem__")
@@ -141,7 +142,7 @@ def decode_polyline(polyline, is3d=False):
141142
:rtype: dict
142143
"""
143144
points = []
144-
index = lat = lng = z= 0
145+
index = lat = lng = z = 0
145146

146147
while index < len(polyline):
147148
result = 1
@@ -165,7 +166,7 @@ def decode_polyline(polyline, is3d=False):
165166
if b < 0x1f:
166167
break
167168
lng += ~(result >> 1) if (result & 1) != 0 else (result >> 1)
168-
169+
169170
if is3d:
170171
result = 1
171172
shift = 0
@@ -179,13 +180,13 @@ def decode_polyline(polyline, is3d=False):
179180
if (result & 1) != 0:
180181
z += ~(result >> 1)
181182
else:
182-
z += (result >> 1)
183-
184-
points.append([round(lng * 1e-5, 6), round(lat * 1e-5, 6), round(z*1e-2,1)])
185-
183+
z += (result >> 1)
184+
185+
points.append([round(lng * 1e-5, 6), round(lat * 1e-5, 6), round(z * 1e-2, 1)])
186+
186187
else:
187188
points.append([round(lng * 1e-5, 6), round(lat * 1e-5, 6)])
188-
189+
189190
geojson = {u'type': u'LineString', u'coordinates': points}
190191

191192
return geojson

openrouteservice/deprecation.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717

1818
import warnings
1919

20+
2021
def warning(old_name, new_name):
22+
"""Deprecation warning"""
23+
2124
warnings.warn('{} will be deprecated in v2.0. Please use {} instead'.format(old_name, new_name),
2225
DeprecationWarning,
2326
stacklevel=2)

openrouteservice/directions.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from openrouteservice import validator, deprecation
2323

24+
2425
def directions(client,
2526
coordinates,
2627
profile='driving-car',

0 commit comments

Comments
 (0)