/
utils.py
364 lines (293 loc) · 11.3 KB
/
utils.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# -*- coding: utf-8 -*-
"""Package helper functions and classes.
Copyright (c) 2019 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from future import standard_library
standard_library.install_aliases()
native_str = str
import json
import mimetypes
import os
import sys
import urllib.parse
from builtins import *
from collections import OrderedDict, namedtuple
from datetime import datetime, timedelta, tzinfo
from past.builtins import basestring
from .exceptions import (
ApiError, RateLimitError,
)
from .response_codes import RATE_LIMIT_RESPONSE_CODE
EncodableFile = namedtuple('EncodableFile',
['file_name', 'file_object', 'content_type'])
def to_unicode(string):
"""Convert a string (bytes, str or unicode) to unicode."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, bytes):
return string.decode('utf-8')
else:
return string
else:
if isinstance(string, str):
return string.decode('utf-8')
else:
return string
def to_bytes(string):
"""Convert a string (bytes, str or unicode) to bytes."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, str):
return string.encode('utf-8')
else:
return string
else:
if isinstance(string, unicode):
return string.encode('utf-8')
else:
return string
def validate_base_url(base_url):
"""Verify that base_url specifies a protocol and network location."""
parsed_url = urllib.parse.urlparse(base_url)
if parsed_url.scheme and parsed_url.netloc:
return parsed_url.geturl()
else:
error_message = "base_url must contain a valid scheme (protocol " \
"specifier) and network location (hostname)"
raise ValueError(error_message)
def is_web_url(string):
"""Check to see if string is an validly-formatted web url."""
assert isinstance(string, basestring)
parsed_url = urllib.parse.urlparse(string)
return (
(
parsed_url.scheme.lower() == 'http'
or parsed_url.scheme.lower() == 'https'
)
and parsed_url.netloc
)
def is_local_file(string):
"""Check to see if string is a valid local file path."""
assert isinstance(string, basestring)
return os.path.isfile(string)
def open_local_file(file_path):
"""Open the file and return an EncodableFile tuple."""
assert isinstance(file_path, basestring)
assert is_local_file(file_path)
file_name = os.path.basename(file_path)
file_object = open(file_path, 'rb')
content_type = mimetypes.guess_type(file_name)[0] or 'text/plain'
return EncodableFile(file_name=file_name,
file_object=file_object,
content_type=content_type)
def check_type(o, acceptable_types, may_be_none=True):
"""Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
TypeError: If the object is None and may_be_none=False, or if the
object is not an instance of one of the acceptable types.
"""
if not isinstance(acceptable_types, tuple):
acceptable_types = (acceptable_types,)
if may_be_none and o is None:
# Object is None, and that is OK!
pass
elif isinstance(o, acceptable_types):
# Object is an instance of an acceptable type.
pass
else:
# Object is something else.
error_message = (
"We were expecting to receive an instance of one of the following "
"types: {types}{none}; but instead we received {o} which is a "
"{o_type}.".format(
types=", ".join([repr(t.__name__) for t in acceptable_types]),
none="or 'None'" if may_be_none else "",
o=o,
o_type=repr(type(o).__name__)
)
)
raise TypeError(error_message)
def dict_from_items_with_values(*dictionaries, **items):
"""Creates a dict with the inputted items; pruning any that are `None`.
Args:
*dictionaries(dict): Dictionaries of items to be pruned and included.
**items: Items to be pruned and included.
Returns:
dict: A dictionary containing all of the items with a 'non-None' value.
"""
dict_list = list(dictionaries)
dict_list.append(items)
result = {}
for d in dict_list:
for key, value in d.items():
if value is not None:
result[key] = value
return result
def raise_if_extra_kwargs(kwargs):
"""Raise a TypeError if kwargs is not empty."""
if kwargs:
raise TypeError("Unexpected **kwargs: {!r}".format(kwargs))
def check_response_code(response, expected_response_code):
"""Check response code against the expected code; raise ApiError.
Checks the requests.response.status_code against the provided expected
response code (erc), and raises a ApiError if they do not match.
Args:
response(requests.response): The response object returned by a request
using the requests package.
expected_response_code(int): The expected response code (HTTP response
code).
Raises:
ApiError: If the requests.response.status_code does not match the
provided expected response code (erc).
"""
if response.status_code in expected_response_code:
pass
elif response.status_code == RATE_LIMIT_RESPONSE_CODE:
raise RateLimitError(response)
else:
raise ApiError(response)
def extract_and_parse_json(response):
"""Extract and parse the JSON data from an requests.response object.
Args:
response(requests.response): The response object returned by a request
using the requests package.
stream(bool): If the request was to get a raw response content
Returns:
The parsed JSON data as the appropriate native Python data type.
Raises:
JSONDecodeError: caused by json.loads
TypeError: caused by json.loads
"""
try:
return json.loads(response.text, object_hook=OrderedDict)
except Exception as e:
raise e
def json_dict(json_data):
"""Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string.
"""
if isinstance(json_data, dict):
return json_data
elif isinstance(json_data, basestring):
return json.loads(json_data, object_hook=OrderedDict)
elif isinstance(json_data, list):
return json_data
else:
raise TypeError(
"'json_data' must be a dictionary or valid JSON string; "
"received: {!r}".format(json_data)
)
def apply_path_params(URL, path_params):
if isinstance(URL, str) and isinstance(path_params, dict):
for k in path_params:
URL = URL.replace('${' + k + '}', str(path_params[k]))
return URL
else:
raise TypeError(
"'URL' must be a string; "
"'path_params' must be a dictionary or valid JSON string; "
"received: (URL={}, path_params={})".format(URL, path_params)
)
def pprint_request_info(url, method, _headers, **kwargs):
debug_print = (
"\nRequest"
"\n\tURL: {}"
"\n\tMethod: {}"
"\n\tHeaders: \n{}"
)
_headers.update(kwargs.get('headers', {}))
_headers = '\n'.join(['\t\t{}: {}'.format(a, b)
for a, b in _headers.items()])
debug_print = debug_print.format(url, method, _headers)
kwargs_to_include = ['params', 'json', 'data', 'stream']
kwargs_pprint = {
'params': 'Params', 'json': 'Body',
'data': 'Body', 'stream': 'Stream'
}
for kw in kwargs_to_include:
if kwargs.get(kw) is not None and kwargs_pprint.get(kw):
value = kwargs.get(kw)
key = kwargs_pprint.get(kw)
if isinstance(value, list) or isinstance(value, dict):
value = json.dumps(value, indent=4)
lines = [' ' * (8 + len(key)) + line
for line in value.split('\n')]
value = '\n'.join(lines)
else:
value = '\t\t{}'.format(value)
format_str = '{}\n\t{}:\n{}'
debug_print = format_str.format(debug_print,
key,
value)
return debug_print
def pprint_response_info(response):
debug_print = (
"\nResponse"
"\n\tStatus: {} - {}"
"\n\tHeaders: \n{}"
)
headers = response.headers
headers = '\n'.join(['\t\t{}: {}'.format(a, b)
for a, b in headers.items()])
body = None
file_resp_headers = ['Content-Disposition', 'fileName']
if 'application/json' in response.headers.get('Content-Type'):
try:
body = response.json()
body = json.dumps(body, indent=4)
body = '\n'.join([' ' * 13 + line for line in body.split('\n')])
except Exception:
body = response.text or response.content
pass
elif any([i in response.headers for i in file_resp_headers]):
body = None
else:
body = response.text or response.content
debug_print = debug_print.format(response.status_code,
response.reason,
headers)
if body is not None:
format_str = '{}\n\t{}:\n{}'
debug_print = format_str.format(debug_print, 'Body', body)
return debug_print
def dict_of_str(json_dict):
"""Given a dictionary; return a new dictionary with all items as strings.
Args:
json_dict(dict): Input JSON dictionary.
Returns:
A Python dictionary with the contents of the JSON object as strings.
"""
result = {}
for key, value in json_dict.items():
result[key] = '{}'.format(value)
return result