/
client.py
236 lines (185 loc) · 7.49 KB
/
client.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
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import time
import solvebio
from .version import VERSION
from .errors import SolveError
from .utils.validators import validate_api_host_url
import platform
import requests
import textwrap
import logging
from requests.auth import AuthBase
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
# Try using pyopenssl if available.
# Requires: pip install pyopenssl ndg-httpsclient pyasn1
# See http://urllib3.readthedocs.org/en/latest/contrib.html#module-urllib3.contrib.pyopenssl # noqa
try:
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
pass
logger = logging.getLogger('solvebio')
def _handle_api_error(response):
if response.status_code not in [400, 401, 403, 404]:
logger.info('API Error: %d' % response.status_code)
raise SolveError(response=response)
def _handle_request_error(e):
if isinstance(e, requests.exceptions.RequestException):
msg = SolveError.default_message
err = "%s: %s" % (type(e).__name__, str(e))
else:
msg = ("Unexpected error communicating with SolveBio.\n"
"It looks like there's probably a configuration "
"issue locally.\nIf this problem persists, let us "
"know at support@solvebio.com.")
err = "A %s was raised" % (type(e).__name__,)
if str(e):
err += " with error message %s" % (str(e),)
else:
err += " with no error message"
msg = textwrap.fill(msg) + "\n\n(Network error: %s)" % (err,)
raise SolveError(message=msg)
class SolveTokenAuth(AuthBase):
"""Custom auth handler for SolveBio API token authentication"""
def __init__(self, token=None, token_type='Token'):
self.token = token
self.token_type = token_type
if not self.token:
# Prefer the OAuth2 access token over the API key.
if solvebio.access_token:
self.token_type = 'Bearer'
self.token = solvebio.access_token
elif solvebio.api_key:
self.token_type = 'Token'
self.token = solvebio.api_key
def __call__(self, r):
if self.token:
r.headers['Authorization'] = '{0} {1}'.format(self.token_type,
self.token)
return r
def __repr__(self):
return '<SolveTokenAuth {0} {1}>'.format(self.token_type, self.token)
class SolveClient(object):
"""A requests-based HTTP client for SolveBio API resources"""
def __init__(self, api_host=None, token=None, token_type='Token'):
self._api_host = api_host
self._token = token
self._token_type = token_type
self._headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Encoding': 'gzip,deflate',
'User-Agent': 'SolveBio Python Client %s [Python %s/%s]' % (
VERSION,
platform.python_implementation(),
platform.python_version()
)
}
def get(self, url, params, **kwargs):
"""Issues an HTTP GET across the wire via the Python requests
library. See *request()* for information on keyword args."""
kwargs['params'] = params
return self.request('GET', url, **kwargs)
def post(self, url, data, **kwargs):
"""Issues an HTTP POST across the wire via the Python requests
library. See *request* for information on keyword args."""
kwargs['data'] = data
return self.request('POST', url, **kwargs)
def delete(self, url, data, **kwargs):
"""Issues an HTTP DELETE across the wire via the Python requests
library. See *request* for information on keyword args."""
kwargs['data'] = data
return self.request('DELETE', url, **kwargs)
def request(self, method, url, **kwargs):
"""
Issues an HTTP Request across the wire via the Python requests
library.
Parameters
----------
method : str
an HTTP method: GET, PUT, POST, DELETE, ...
url : str
the place to connect to. If the url doesn't start
with a protocol (https:// or http://), we'll slap
solvebio.api_host in the front.
allow_redirects: bool, optional
set *False* we won't follow any redirects
auth: function, optional
Function to call to get an Authorization key.
If not given we'll use self._token.
headers: dict, optional
Custom headers can be provided here; generally though this
will be set correctly by default dependent on the
method type. If the content type is JSON, we'll
JSON-encode params.
param : dict, optional
passed as *params* in the requests.request
timeout : int, optional
timeout value in seconds for the request
raw: bool, optional
unless *True* the response encoded to json
files: file
File content in the form of a file handle which is to be
uploaded. Files are passed in POST requests
Returns
-------
response object. If *raw* is not *True* and
repsonse if valid the object will be JSON encoded. Otherwise
it will be the request.reposne object.
"""
opts = {
'allow_redirects': True,
'auth': SolveTokenAuth(self._token, self._token_type),
'data': {},
'files': None,
'headers': dict(self._headers),
'params': {},
'timeout': 80,
'verify': True
}
raw = kwargs.pop('raw', False)
debug = kwargs.pop('debug', False)
opts.update(kwargs)
method = method.upper()
if opts['files']:
# Don't use application/json for file uploads or GET requests
opts['headers'].pop('Content-Type', None)
else:
opts['data'] = json.dumps(opts['data'])
# Expand URL with API host if none was given
api_host = self._api_host or solvebio.api_host
# validate API host
validate_api_host_url(api_host)
if not url.startswith(api_host):
url = urljoin(api_host, url)
logger.debug('API %s Request: %s' % (method, url))
if debug:
self._log_raw_request(method, url, **opts)
try:
response = requests.request(method, url, **opts)
except Exception as e:
_handle_request_error(e)
if 429 == response.status_code:
delay = int(response.headers['retry-after']) + 1
logger.warn('Too many requests. Retrying in {0}s.'.format(delay))
time.sleep(delay)
return self.request(method, url, **kwargs)
if not (200 <= response.status_code < 400):
_handle_api_error(response)
# 204 is used on deletion. There is no JSON here.
if raw or response.status_code in [204, 301, 302]:
return response
return response.json()
def _log_raw_request(self, method, url, **kwargs):
from requests import Request, Session
req = Request(method=method.upper(), url=url,
data=kwargs['data'], params=kwargs['params'])
prepped = Session().prepare_request(req, )
logger.debug(prepped.headers)
logger.debug(prepped.body)
client = SolveClient()