|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +{{>partial_header}} |
| 4 | + |
| 5 | + |
| 6 | +import io |
| 7 | +import json |
| 8 | +import re |
| 9 | +import ssl |
| 10 | +from typing import Optional, Union |
| 11 | + |
| 12 | +import httpx |
| 13 | + |
| 14 | +from {{packageName}}.exceptions import ApiException, ApiValueError |
| 15 | + |
| 16 | +RESTResponseType = httpx.Response |
| 17 | + |
| 18 | +class RESTResponse(io.IOBase): |
| 19 | + |
| 20 | + def __init__(self, resp) -> None: |
| 21 | + self.response = resp |
| 22 | + self.status = resp.status_code |
| 23 | + self.reason = resp.reason_phrase |
| 24 | + self.data = None |
| 25 | + |
| 26 | + async def read(self): |
| 27 | + if self.data is None: |
| 28 | + self.data = await self.response.aread() |
| 29 | + return self.data |
| 30 | + |
| 31 | + def getheaders(self): |
| 32 | + """Returns a CIMultiDictProxy of the response headers.""" |
| 33 | + return self.response.headers |
| 34 | + |
| 35 | + def getheader(self, name, default=None): |
| 36 | + """Returns a given response header.""" |
| 37 | + return self.response.headers.get(name, default) |
| 38 | + |
| 39 | + |
| 40 | +class RESTClientObject: |
| 41 | + |
| 42 | + def __init__(self, configuration) -> None: |
| 43 | + |
| 44 | + # maxsize is number of requests to host that are allowed in parallel |
| 45 | + self.maxsize = configuration.connection_pool_maxsize |
| 46 | + |
| 47 | + self.ssl_context = ssl.create_default_context( |
| 48 | + cafile=configuration.ssl_ca_cert, |
| 49 | + cadata=configuration.ca_cert_data, |
| 50 | + ) |
| 51 | + if configuration.cert_file: |
| 52 | + self.ssl_context.load_cert_chain( |
| 53 | + configuration.cert_file, keyfile=configuration.key_file |
| 54 | + ) |
| 55 | + |
| 56 | + if not configuration.verify_ssl: |
| 57 | + self.ssl_context.check_hostname = False |
| 58 | + self.ssl_context.verify_mode = ssl.CERT_NONE |
| 59 | + |
| 60 | + self.proxy = configuration.proxy |
| 61 | + self.proxy_headers = configuration.proxy_headers |
| 62 | + |
| 63 | + self.pool_manager: Optional[httpx.AsyncClient] = None |
| 64 | + |
| 65 | + async def close(self): |
| 66 | + await self.pool_manager.aclose() |
| 67 | + |
| 68 | + async def request( |
| 69 | + self, |
| 70 | + method, |
| 71 | + url, |
| 72 | + headers=None, |
| 73 | + body=None, |
| 74 | + post_params=None, |
| 75 | + _request_timeout=None): |
| 76 | + """Execute request |
| 77 | + |
| 78 | + :param method: http request method |
| 79 | + :param url: http request url |
| 80 | + :param headers: http request headers |
| 81 | + :param body: request json body, for `application/json` |
| 82 | + :param post_params: request post parameters, |
| 83 | + `application/x-www-form-urlencoded` |
| 84 | + and `multipart/form-data` |
| 85 | + :param _request_timeout: timeout setting for this request. If one |
| 86 | + number provided, it will be total request |
| 87 | + timeout. It can also be a pair (tuple) of |
| 88 | + (connection, read) timeouts. |
| 89 | + """ |
| 90 | + method = method.upper() |
| 91 | + assert method in [ |
| 92 | + 'GET', |
| 93 | + 'HEAD', |
| 94 | + 'DELETE', |
| 95 | + 'POST', |
| 96 | + 'PUT', |
| 97 | + 'PATCH', |
| 98 | + 'OPTIONS' |
| 99 | + ] |
| 100 | + |
| 101 | + if post_params and body: |
| 102 | + raise ApiValueError( |
| 103 | + "body parameter cannot be used with post_params parameter." |
| 104 | + ) |
| 105 | + |
| 106 | + post_params = post_params or {} |
| 107 | + headers = headers or {} |
| 108 | + timeout = _request_timeout or 5 * 60 |
| 109 | + |
| 110 | + if 'Content-Type' not in headers: |
| 111 | + headers['Content-Type'] = 'application/json' |
| 112 | + |
| 113 | + args = { |
| 114 | + "method": method, |
| 115 | + "url": url, |
| 116 | + "timeout": timeout, |
| 117 | + "headers": headers |
| 118 | + } |
| 119 | + |
| 120 | + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` |
| 121 | + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: |
| 122 | + if re.search('json', headers['Content-Type'], re.IGNORECASE): |
| 123 | + if body is not None: |
| 124 | + args["json"] = body |
| 125 | + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 |
| 126 | + args["data"] = dict(post_params) |
| 127 | + elif headers['Content-Type'] == 'multipart/form-data': |
| 128 | + # must del headers['Content-Type'], or the correct |
| 129 | + # Content-Type which generated by httpx |
| 130 | + del headers['Content-Type'] |
| 131 | + |
| 132 | + files = [] |
| 133 | + data = {} |
| 134 | + for param in post_params: |
| 135 | + k, v = param |
| 136 | + if isinstance(v, tuple) and len(v) == 3: |
| 137 | + files.append((k, v)) |
| 138 | + else: |
| 139 | + # Ensures that dict objects are serialized |
| 140 | + if isinstance(v, dict): |
| 141 | + v = json.dumps(v) |
| 142 | + elif isinstance(v, int): |
| 143 | + v = str(v) |
| 144 | + data[k] = v |
| 145 | + |
| 146 | + if files: |
| 147 | + args["files"] = files |
| 148 | + if data: |
| 149 | + args["data"] = data |
| 150 | + |
| 151 | + # Pass a `bytes` parameter directly in the body to support |
| 152 | + # other content types than Json when `body` argument is provided |
| 153 | + # in serialized form |
| 154 | + elif isinstance(body, str) or isinstance(body, bytes): |
| 155 | + args["data"] = body |
| 156 | + else: |
| 157 | + # Cannot generate the request from given parameters |
| 158 | + msg = """Cannot prepare a request message for provided |
| 159 | + arguments. Please check that your arguments match |
| 160 | + declared content type.""" |
| 161 | + raise ApiException(status=0, reason=msg) |
| 162 | + |
| 163 | + if self.pool_manager is None: |
| 164 | + self.pool_manager = self._create_pool_manager() |
| 165 | + |
| 166 | + r = await self.pool_manager.request(**args) |
| 167 | + return RESTResponse(r) |
| 168 | + |
| 169 | + def _create_pool_manager(self) -> httpx.AsyncClient: |
| 170 | + limits = httpx.Limits(max_connections=self.maxsize) |
| 171 | + |
| 172 | + proxy = None |
| 173 | + if self.proxy: |
| 174 | + proxy = httpx.Proxy( |
| 175 | + url=self.proxy, |
| 176 | + headers=self.proxy_headers |
| 177 | + ) |
| 178 | + |
| 179 | + return httpx.AsyncClient( |
| 180 | + limits=limits, |
| 181 | + proxy=proxy, |
| 182 | + verify=self.ssl_context, |
| 183 | + trust_env=True |
| 184 | + ) |
0 commit comments