|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +{{>partial_header}} |
| 4 | + |
| 5 | +from __future__ import absolute_import |
| 6 | + |
| 7 | +import io |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import re |
| 11 | +import ssl |
| 12 | + |
| 13 | +import certifi |
| 14 | +# python 2 and python 3 compatibility library |
| 15 | +import six |
| 16 | +from six.moves.urllib.parse import urlencode |
| 17 | + |
| 18 | +try: |
| 19 | + import urllib3 |
| 20 | +except ImportError: |
| 21 | + raise ImportError('Swagger python client requires urllib3.') |
| 22 | + |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +class RESTResponse(io.IOBase): |
| 28 | + |
| 29 | + def __init__(self, resp): |
| 30 | + self.urllib3_response = resp |
| 31 | + self.status = resp.status |
| 32 | + self.reason = resp.reason |
| 33 | + self.data = resp.data |
| 34 | + |
| 35 | + def getheaders(self): |
| 36 | + """Returns a dictionary of the response headers.""" |
| 37 | + return self.urllib3_response.headers |
| 38 | + |
| 39 | + def getheader(self, name, default=None): |
| 40 | + """Returns a given response header.""" |
| 41 | + return self.urllib3_response.headers.get(name, default) |
| 42 | + |
| 43 | + |
| 44 | +class RESTClientObject(object): |
| 45 | + |
| 46 | + def __init__(self, configuration, pools_size=4, maxsize=None): |
| 47 | + # urllib3.PoolManager will pass all kw parameters to connectionpool |
| 48 | + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 |
| 49 | + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 |
| 50 | + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 |
| 51 | + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 |
| 52 | + |
| 53 | + # cert_reqs |
| 54 | + if configuration.verify_ssl: |
| 55 | + cert_reqs = ssl.CERT_REQUIRED |
| 56 | + else: |
| 57 | + cert_reqs = ssl.CERT_NONE |
| 58 | + |
| 59 | + # ca_certs |
| 60 | + if configuration.ssl_ca_cert: |
| 61 | + ca_certs = configuration.ssl_ca_cert |
| 62 | + else: |
| 63 | + # if not set certificate file, use Mozilla's root certificates. |
| 64 | + ca_certs = certifi.where() |
| 65 | + |
| 66 | + addition_pool_args = {} |
| 67 | + if configuration.assert_hostname is not None: |
| 68 | + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 |
| 69 | + |
| 70 | + if maxsize is None: |
| 71 | + if configuration.connection_pool_maxsize is not None: |
| 72 | + maxsize = configuration.connection_pool_maxsize |
| 73 | + else: |
| 74 | + maxsize = 4 |
| 75 | + |
| 76 | + # https pool manager |
| 77 | + if configuration.proxy: |
| 78 | + self.pool_manager = urllib3.ProxyManager( |
| 79 | + num_pools=pools_size, |
| 80 | + maxsize=maxsize, |
| 81 | + cert_reqs=cert_reqs, |
| 82 | + ca_certs=ca_certs, |
| 83 | + cert_file=configuration.cert_file, |
| 84 | + key_file=configuration.key_file, |
| 85 | + proxy_url=configuration.proxy, |
| 86 | + **addition_pool_args |
| 87 | + ) |
| 88 | + else: |
| 89 | + self.pool_manager = urllib3.PoolManager( |
| 90 | + num_pools=pools_size, |
| 91 | + maxsize=maxsize, |
| 92 | + cert_reqs=cert_reqs, |
| 93 | + ca_certs=ca_certs, |
| 94 | + cert_file=configuration.cert_file, |
| 95 | + key_file=configuration.key_file, |
| 96 | + **addition_pool_args |
| 97 | + ) |
| 98 | + |
| 99 | + def request(self, method, url, query_params=None, headers=None, |
| 100 | + body=None, post_params=None, _preload_content=True, |
| 101 | + _request_timeout=None): |
| 102 | + """Perform requests. |
| 103 | + |
| 104 | + :param method: http request method |
| 105 | + :param url: http request url |
| 106 | + :param query_params: query parameters in the url |
| 107 | + :param headers: http request headers |
| 108 | + :param body: request json body, for `application/json` |
| 109 | + :param post_params: request post parameters, |
| 110 | + `application/x-www-form-urlencoded` |
| 111 | + and `multipart/form-data` |
| 112 | + :param _preload_content: if False, the urllib3.HTTPResponse object will |
| 113 | + be returned without reading/decoding response |
| 114 | + data. Default is True. |
| 115 | + :param _request_timeout: timeout setting for this request. If one |
| 116 | + number provided, it will be total request |
| 117 | + timeout. It can also be a pair (tuple) of |
| 118 | + (connection, read) timeouts. |
| 119 | + """ |
| 120 | + method = method.upper() |
| 121 | + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', |
| 122 | + 'PATCH', 'OPTIONS'] |
| 123 | + |
| 124 | + if post_params and body: |
| 125 | + raise ValueError( |
| 126 | + "body parameter cannot be used with post_params parameter." |
| 127 | + ) |
| 128 | + |
| 129 | + post_params = post_params or {} |
| 130 | + headers = headers or {} |
| 131 | + |
| 132 | + timeout = None |
| 133 | + if _request_timeout: |
| 134 | + if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 |
| 135 | + timeout = urllib3.Timeout(total=_request_timeout) |
| 136 | + elif (isinstance(_request_timeout, tuple) and |
| 137 | + len(_request_timeout) == 2): |
| 138 | + timeout = urllib3.Timeout( |
| 139 | + connect=_request_timeout[0], read=_request_timeout[1]) |
| 140 | + |
| 141 | + if 'Content-Type' not in headers: |
| 142 | + headers['Content-Type'] = 'application/json' |
| 143 | + |
| 144 | + try: |
| 145 | + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` |
| 146 | + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: |
| 147 | + if query_params: |
| 148 | + url += '?' + urlencode(query_params) |
| 149 | + if re.search('json', headers['Content-Type'], re.IGNORECASE): |
| 150 | + request_body = '{}' |
| 151 | + if body is not None: |
| 152 | + request_body = json.dumps(body) |
| 153 | + r = self.pool_manager.request( |
| 154 | + method, url, |
| 155 | + body=request_body, |
| 156 | + preload_content=_preload_content, |
| 157 | + timeout=timeout, |
| 158 | + headers=headers) |
| 159 | + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 |
| 160 | + r = self.pool_manager.request( |
| 161 | + method, url, |
| 162 | + fields=post_params, |
| 163 | + encode_multipart=False, |
| 164 | + preload_content=_preload_content, |
| 165 | + timeout=timeout, |
| 166 | + headers=headers) |
| 167 | + elif headers['Content-Type'] == 'multipart/form-data': |
| 168 | + # must del headers['Content-Type'], or the correct |
| 169 | + # Content-Type which generated by urllib3 will be |
| 170 | + # overwritten. |
| 171 | + del headers['Content-Type'] |
| 172 | + r = self.pool_manager.request( |
| 173 | + method, url, |
| 174 | + fields=post_params, |
| 175 | + encode_multipart=True, |
| 176 | + preload_content=_preload_content, |
| 177 | + timeout=timeout, |
| 178 | + headers=headers) |
| 179 | + # Pass a `string` parameter directly in the body to support |
| 180 | + # other content types than Json when `body` argument is |
| 181 | + # provided in serialized form |
| 182 | + elif isinstance(body, str): |
| 183 | + request_body = body |
| 184 | + r = self.pool_manager.request( |
| 185 | + method, url, |
| 186 | + body=request_body, |
| 187 | + preload_content=_preload_content, |
| 188 | + timeout=timeout, |
| 189 | + headers=headers) |
| 190 | + else: |
| 191 | + # Cannot generate the request from given parameters |
| 192 | + msg = """Cannot prepare a request message for provided |
| 193 | + arguments. Please check that your arguments match |
| 194 | + declared content type.""" |
| 195 | + raise ApiException(status=0, reason=msg) |
| 196 | + # For `GET`, `HEAD` |
| 197 | + else: |
| 198 | + r = self.pool_manager.request(method, url, |
| 199 | + fields=query_params, |
| 200 | + preload_content=_preload_content, |
| 201 | + timeout=timeout, |
| 202 | + headers=headers) |
| 203 | + except urllib3.exceptions.SSLError as e: |
| 204 | + msg = "{0}\n{1}".format(type(e).__name__, str(e)) |
| 205 | + raise ApiException(status=0, reason=msg) |
| 206 | + |
| 207 | + if _preload_content: |
| 208 | + r = RESTResponse(r) |
| 209 | + |
| 210 | + # log response body |
| 211 | + logger.debug("response body: %s", r.data) |
| 212 | + |
| 213 | + if not 200 <= r.status <= 299: |
| 214 | + raise ApiException(http_resp=r) |
| 215 | + |
| 216 | + return r |
| 217 | + |
| 218 | + def GET(self, url, headers=None, query_params=None, _preload_content=True, |
| 219 | + _request_timeout=None): |
| 220 | + return self.request("GET", url, |
| 221 | + headers=headers, |
| 222 | + _preload_content=_preload_content, |
| 223 | + _request_timeout=_request_timeout, |
| 224 | + query_params=query_params) |
| 225 | + |
| 226 | + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, |
| 227 | + _request_timeout=None): |
| 228 | + return self.request("HEAD", url, |
| 229 | + headers=headers, |
| 230 | + _preload_content=_preload_content, |
| 231 | + _request_timeout=_request_timeout, |
| 232 | + query_params=query_params) |
| 233 | + |
| 234 | + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, |
| 235 | + body=None, _preload_content=True, _request_timeout=None): |
| 236 | + return self.request("OPTIONS", url, |
| 237 | + headers=headers, |
| 238 | + query_params=query_params, |
| 239 | + post_params=post_params, |
| 240 | + _preload_content=_preload_content, |
| 241 | + _request_timeout=_request_timeout, |
| 242 | + body=body) |
| 243 | + |
| 244 | + def DELETE(self, url, headers=None, query_params=None, body=None, |
| 245 | + _preload_content=True, _request_timeout=None): |
| 246 | + return self.request("DELETE", url, |
| 247 | + headers=headers, |
| 248 | + query_params=query_params, |
| 249 | + _preload_content=_preload_content, |
| 250 | + _request_timeout=_request_timeout, |
| 251 | + body=body) |
| 252 | + |
| 253 | + def POST(self, url, headers=None, query_params=None, post_params=None, |
| 254 | + body=None, _preload_content=True, _request_timeout=None): |
| 255 | + return self.request("POST", url, |
| 256 | + headers=headers, |
| 257 | + query_params=query_params, |
| 258 | + post_params=post_params, |
| 259 | + _preload_content=_preload_content, |
| 260 | + _request_timeout=_request_timeout, |
| 261 | + body=body) |
| 262 | + |
| 263 | + def PUT(self, url, headers=None, query_params=None, post_params=None, |
| 264 | + body=None, _preload_content=True, _request_timeout=None): |
| 265 | + return self.request("PUT", url, |
| 266 | + headers=headers, |
| 267 | + query_params=query_params, |
| 268 | + post_params=post_params, |
| 269 | + _preload_content=_preload_content, |
| 270 | + _request_timeout=_request_timeout, |
| 271 | + body=body) |
| 272 | + |
| 273 | + def PATCH(self, url, headers=None, query_params=None, post_params=None, |
| 274 | + body=None, _preload_content=True, _request_timeout=None): |
| 275 | + return self.request("PATCH", url, |
| 276 | + headers=headers, |
| 277 | + query_params=query_params, |
| 278 | + post_params=post_params, |
| 279 | + _preload_content=_preload_content, |
| 280 | + _request_timeout=_request_timeout, |
| 281 | + body=body) |
| 282 | + |
| 283 | + |
| 284 | +class ApiException(Exception): |
| 285 | + |
| 286 | + def __init__(self, status=None, reason=None, http_resp=None): |
| 287 | + if http_resp: |
| 288 | + self.status = http_resp.status |
| 289 | + self.reason = http_resp.reason |
| 290 | + self.body = http_resp.data |
| 291 | + self.headers = http_resp.getheaders() |
| 292 | + else: |
| 293 | + self.status = status |
| 294 | + self.reason = reason |
| 295 | + self.body = None |
| 296 | + self.headers = None |
| 297 | + |
| 298 | + def __str__(self): |
| 299 | + """Custom error messages for exception""" |
| 300 | + error_message = "({0})\n"\ |
| 301 | + "Reason: {1}\n".format(self.status, self.reason) |
| 302 | + if self.headers: |
| 303 | + error_message += "HTTP response headers: {0}\n".format( |
| 304 | + self.headers) |
| 305 | + |
| 306 | + if self.body: |
| 307 | + error_message += "HTTP response body: {0}\n".format(self.body) |
| 308 | + |
| 309 | + return error_message |
0 commit comments