vectorize_client.rest

Vectorize API (Beta)

API for Vectorize services

The version of the OpenAPI document: 0.0.1 Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.

  1# coding: utf-8
  2
  3"""
  4    Vectorize API (Beta)
  5
  6    API for Vectorize services
  7
  8    The version of the OpenAPI document: 0.0.1
  9    Generated by OpenAPI Generator (https://openapi-generator.tech)
 10
 11    Do not edit the class manually.
 12"""  # noqa: E501
 13
 14
 15import io
 16import json
 17import re
 18import ssl
 19
 20import urllib3
 21
 22from vectorize_client.exceptions import ApiException, ApiValueError
 23
 24SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"}
 25RESTResponseType = urllib3.HTTPResponse
 26
 27
 28def is_socks_proxy_url(url):
 29    if url is None:
 30        return False
 31    split_section = url.split("://")
 32    if len(split_section) < 2:
 33        return False
 34    else:
 35        return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
 36
 37
 38class RESTResponse(io.IOBase):
 39
 40    def __init__(self, resp) -> None:
 41        self.response = resp
 42        self.status = resp.status
 43        self.reason = resp.reason
 44        self.data = None
 45
 46    def read(self):
 47        if self.data is None:
 48            self.data = self.response.data
 49        return self.data
 50
 51    def getheaders(self):
 52        """Returns a dictionary of the response headers."""
 53        return self.response.headers
 54
 55    def getheader(self, name, default=None):
 56        """Returns a given response header."""
 57        return self.response.headers.get(name, default)
 58
 59
 60class RESTClientObject:
 61
 62    def __init__(self, configuration) -> None:
 63        # urllib3.PoolManager will pass all kw parameters to connectionpool
 64        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75  # noqa: E501
 65        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680  # noqa: E501
 66        # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html  # noqa: E501
 67
 68        # cert_reqs
 69        if configuration.verify_ssl:
 70            cert_reqs = ssl.CERT_REQUIRED
 71        else:
 72            cert_reqs = ssl.CERT_NONE
 73
 74        pool_args = {
 75            "cert_reqs": cert_reqs,
 76            "ca_certs": configuration.ssl_ca_cert,
 77            "cert_file": configuration.cert_file,
 78            "key_file": configuration.key_file,
 79        }
 80        if configuration.assert_hostname is not None:
 81            pool_args['assert_hostname'] = (
 82                configuration.assert_hostname
 83            )
 84
 85        if configuration.retries is not None:
 86            pool_args['retries'] = configuration.retries
 87
 88        if configuration.tls_server_name:
 89            pool_args['server_hostname'] = configuration.tls_server_name
 90
 91
 92        if configuration.socket_options is not None:
 93            pool_args['socket_options'] = configuration.socket_options
 94
 95        if configuration.connection_pool_maxsize is not None:
 96            pool_args['maxsize'] = configuration.connection_pool_maxsize
 97
 98        # https pool manager
 99        self.pool_manager: urllib3.PoolManager
100
101        if configuration.proxy:
102            if is_socks_proxy_url(configuration.proxy):
103                from urllib3.contrib.socks import SOCKSProxyManager
104                pool_args["proxy_url"] = configuration.proxy
105                pool_args["headers"] = configuration.proxy_headers
106                self.pool_manager = SOCKSProxyManager(**pool_args)
107            else:
108                pool_args["proxy_url"] = configuration.proxy
109                pool_args["proxy_headers"] = configuration.proxy_headers
110                self.pool_manager = urllib3.ProxyManager(**pool_args)
111        else:
112            self.pool_manager = urllib3.PoolManager(**pool_args)
113
114    def request(
115        self,
116        method,
117        url,
118        headers=None,
119        body=None,
120        post_params=None,
121        _request_timeout=None
122    ):
123        """Perform requests.
124
125        :param method: http request method
126        :param url: http request url
127        :param headers: http request headers
128        :param body: request json body, for `application/json`
129        :param post_params: request post parameters,
130                            `application/x-www-form-urlencoded`
131                            and `multipart/form-data`
132        :param _request_timeout: timeout setting for this request. If one
133                                 number provided, it will be total request
134                                 timeout. It can also be a pair (tuple) of
135                                 (connection, read) timeouts.
136        """
137        method = method.upper()
138        assert method in [
139            'GET',
140            'HEAD',
141            'DELETE',
142            'POST',
143            'PUT',
144            'PATCH',
145            'OPTIONS'
146        ]
147
148        if post_params and body:
149            raise ApiValueError(
150                "body parameter cannot be used with post_params parameter."
151            )
152
153        post_params = post_params or {}
154        headers = headers or {}
155
156        timeout = None
157        if _request_timeout:
158            if isinstance(_request_timeout, (int, float)):
159                timeout = urllib3.Timeout(total=_request_timeout)
160            elif (
161                    isinstance(_request_timeout, tuple)
162                    and len(_request_timeout) == 2
163                ):
164                timeout = urllib3.Timeout(
165                    connect=_request_timeout[0],
166                    read=_request_timeout[1]
167                )
168
169        try:
170            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
171            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
172
173                # no content type provided or payload is json
174                content_type = headers.get('Content-Type')
175                if (
176                    not content_type
177                    or re.search('json', content_type, re.IGNORECASE)
178                ):
179                    request_body = None
180                    if body is not None:
181                        request_body = json.dumps(body)
182                    r = self.pool_manager.request(
183                        method,
184                        url,
185                        body=request_body,
186                        timeout=timeout,
187                        headers=headers,
188                        preload_content=False
189                    )
190                elif content_type == 'application/x-www-form-urlencoded':
191                    r = self.pool_manager.request(
192                        method,
193                        url,
194                        fields=post_params,
195                        encode_multipart=False,
196                        timeout=timeout,
197                        headers=headers,
198                        preload_content=False
199                    )
200                elif content_type == 'multipart/form-data':
201                    # must del headers['Content-Type'], or the correct
202                    # Content-Type which generated by urllib3 will be
203                    # overwritten.
204                    del headers['Content-Type']
205                    # Ensures that dict objects are serialized
206                    post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
207                    r = self.pool_manager.request(
208                        method,
209                        url,
210                        fields=post_params,
211                        encode_multipart=True,
212                        timeout=timeout,
213                        headers=headers,
214                        preload_content=False
215                    )
216                # Pass a `string` parameter directly in the body to support
217                # other content types than JSON when `body` argument is
218                # provided in serialized form.
219                elif isinstance(body, str) or isinstance(body, bytes):
220                    r = self.pool_manager.request(
221                        method,
222                        url,
223                        body=body,
224                        timeout=timeout,
225                        headers=headers,
226                        preload_content=False
227                    )
228                elif headers['Content-Type'].startswith('text/') and isinstance(body, bool):
229                    request_body = "true" if body else "false"
230                    r = self.pool_manager.request(
231                        method,
232                        url,
233                        body=request_body,
234                        preload_content=False,
235                        timeout=timeout,
236                        headers=headers)
237                else:
238                    # Cannot generate the request from given parameters
239                    msg = """Cannot prepare a request message for provided
240                             arguments. Please check that your arguments match
241                             declared content type."""
242                    raise ApiException(status=0, reason=msg)
243            # For `GET`, `HEAD`
244            else:
245                r = self.pool_manager.request(
246                    method,
247                    url,
248                    fields={},
249                    timeout=timeout,
250                    headers=headers,
251                    preload_content=False
252                )
253        except urllib3.exceptions.SSLError as e:
254            msg = "\n".join([type(e).__name__, str(e)])
255            raise ApiException(status=0, reason=msg)
256
257        return RESTResponse(r)
SUPPORTED_SOCKS_PROXIES = {'socks5', 'socks4a', 'socks5h', 'socks4'}
RESTResponseType = <class 'urllib3.response.HTTPResponse'>
def is_socks_proxy_url(url):
29def is_socks_proxy_url(url):
30    if url is None:
31        return False
32    split_section = url.split("://")
33    if len(split_section) < 2:
34        return False
35    else:
36        return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
class RESTResponse(io.IOBase):
39class RESTResponse(io.IOBase):
40
41    def __init__(self, resp) -> None:
42        self.response = resp
43        self.status = resp.status
44        self.reason = resp.reason
45        self.data = None
46
47    def read(self):
48        if self.data is None:
49            self.data = self.response.data
50        return self.data
51
52    def getheaders(self):
53        """Returns a dictionary of the response headers."""
54        return self.response.headers
55
56    def getheader(self, name, default=None):
57        """Returns a given response header."""
58        return self.response.headers.get(name, default)

The abstract base class for all I/O classes.

This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.

Even though IOBase does not declare read, readinto, or write because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise UnsupportedOperation when operations they do not support are called.

The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. In some cases (such as readinto), a writable object is required. Text I/O classes work with str data.

Note that calling any method (except additional calls to close(), which are ignored) on a closed stream should raise a ValueError.

IOBase (and its subclasses) support the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream.

IOBase also supports the :keyword:with statement. In this example, fp is closed after the suite of the with statement is complete:

with open('spam.txt', 'r') as fp: fp.write('Spam and eggs!')

RESTResponse(resp)
41    def __init__(self, resp) -> None:
42        self.response = resp
43        self.status = resp.status
44        self.reason = resp.reason
45        self.data = None
response
status
reason
data
def read(self):
47    def read(self):
48        if self.data is None:
49            self.data = self.response.data
50        return self.data
def getheaders(self):
52    def getheaders(self):
53        """Returns a dictionary of the response headers."""
54        return self.response.headers

Returns a dictionary of the response headers.

def getheader(self, name, default=None):
56    def getheader(self, name, default=None):
57        """Returns a given response header."""
58        return self.response.headers.get(name, default)

Returns a given response header.

class RESTClientObject:
 61class RESTClientObject:
 62
 63    def __init__(self, configuration) -> None:
 64        # urllib3.PoolManager will pass all kw parameters to connectionpool
 65        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75  # noqa: E501
 66        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680  # noqa: E501
 67        # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html  # noqa: E501
 68
 69        # cert_reqs
 70        if configuration.verify_ssl:
 71            cert_reqs = ssl.CERT_REQUIRED
 72        else:
 73            cert_reqs = ssl.CERT_NONE
 74
 75        pool_args = {
 76            "cert_reqs": cert_reqs,
 77            "ca_certs": configuration.ssl_ca_cert,
 78            "cert_file": configuration.cert_file,
 79            "key_file": configuration.key_file,
 80        }
 81        if configuration.assert_hostname is not None:
 82            pool_args['assert_hostname'] = (
 83                configuration.assert_hostname
 84            )
 85
 86        if configuration.retries is not None:
 87            pool_args['retries'] = configuration.retries
 88
 89        if configuration.tls_server_name:
 90            pool_args['server_hostname'] = configuration.tls_server_name
 91
 92
 93        if configuration.socket_options is not None:
 94            pool_args['socket_options'] = configuration.socket_options
 95
 96        if configuration.connection_pool_maxsize is not None:
 97            pool_args['maxsize'] = configuration.connection_pool_maxsize
 98
 99        # https pool manager
100        self.pool_manager: urllib3.PoolManager
101
102        if configuration.proxy:
103            if is_socks_proxy_url(configuration.proxy):
104                from urllib3.contrib.socks import SOCKSProxyManager
105                pool_args["proxy_url"] = configuration.proxy
106                pool_args["headers"] = configuration.proxy_headers
107                self.pool_manager = SOCKSProxyManager(**pool_args)
108            else:
109                pool_args["proxy_url"] = configuration.proxy
110                pool_args["proxy_headers"] = configuration.proxy_headers
111                self.pool_manager = urllib3.ProxyManager(**pool_args)
112        else:
113            self.pool_manager = urllib3.PoolManager(**pool_args)
114
115    def request(
116        self,
117        method,
118        url,
119        headers=None,
120        body=None,
121        post_params=None,
122        _request_timeout=None
123    ):
124        """Perform requests.
125
126        :param method: http request method
127        :param url: http request url
128        :param headers: http request headers
129        :param body: request json body, for `application/json`
130        :param post_params: request post parameters,
131                            `application/x-www-form-urlencoded`
132                            and `multipart/form-data`
133        :param _request_timeout: timeout setting for this request. If one
134                                 number provided, it will be total request
135                                 timeout. It can also be a pair (tuple) of
136                                 (connection, read) timeouts.
137        """
138        method = method.upper()
139        assert method in [
140            'GET',
141            'HEAD',
142            'DELETE',
143            'POST',
144            'PUT',
145            'PATCH',
146            'OPTIONS'
147        ]
148
149        if post_params and body:
150            raise ApiValueError(
151                "body parameter cannot be used with post_params parameter."
152            )
153
154        post_params = post_params or {}
155        headers = headers or {}
156
157        timeout = None
158        if _request_timeout:
159            if isinstance(_request_timeout, (int, float)):
160                timeout = urllib3.Timeout(total=_request_timeout)
161            elif (
162                    isinstance(_request_timeout, tuple)
163                    and len(_request_timeout) == 2
164                ):
165                timeout = urllib3.Timeout(
166                    connect=_request_timeout[0],
167                    read=_request_timeout[1]
168                )
169
170        try:
171            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
172            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
173
174                # no content type provided or payload is json
175                content_type = headers.get('Content-Type')
176                if (
177                    not content_type
178                    or re.search('json', content_type, re.IGNORECASE)
179                ):
180                    request_body = None
181                    if body is not None:
182                        request_body = json.dumps(body)
183                    r = self.pool_manager.request(
184                        method,
185                        url,
186                        body=request_body,
187                        timeout=timeout,
188                        headers=headers,
189                        preload_content=False
190                    )
191                elif content_type == 'application/x-www-form-urlencoded':
192                    r = self.pool_manager.request(
193                        method,
194                        url,
195                        fields=post_params,
196                        encode_multipart=False,
197                        timeout=timeout,
198                        headers=headers,
199                        preload_content=False
200                    )
201                elif content_type == 'multipart/form-data':
202                    # must del headers['Content-Type'], or the correct
203                    # Content-Type which generated by urllib3 will be
204                    # overwritten.
205                    del headers['Content-Type']
206                    # Ensures that dict objects are serialized
207                    post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
208                    r = self.pool_manager.request(
209                        method,
210                        url,
211                        fields=post_params,
212                        encode_multipart=True,
213                        timeout=timeout,
214                        headers=headers,
215                        preload_content=False
216                    )
217                # Pass a `string` parameter directly in the body to support
218                # other content types than JSON when `body` argument is
219                # provided in serialized form.
220                elif isinstance(body, str) or isinstance(body, bytes):
221                    r = self.pool_manager.request(
222                        method,
223                        url,
224                        body=body,
225                        timeout=timeout,
226                        headers=headers,
227                        preload_content=False
228                    )
229                elif headers['Content-Type'].startswith('text/') and isinstance(body, bool):
230                    request_body = "true" if body else "false"
231                    r = self.pool_manager.request(
232                        method,
233                        url,
234                        body=request_body,
235                        preload_content=False,
236                        timeout=timeout,
237                        headers=headers)
238                else:
239                    # Cannot generate the request from given parameters
240                    msg = """Cannot prepare a request message for provided
241                             arguments. Please check that your arguments match
242                             declared content type."""
243                    raise ApiException(status=0, reason=msg)
244            # For `GET`, `HEAD`
245            else:
246                r = self.pool_manager.request(
247                    method,
248                    url,
249                    fields={},
250                    timeout=timeout,
251                    headers=headers,
252                    preload_content=False
253                )
254        except urllib3.exceptions.SSLError as e:
255            msg = "\n".join([type(e).__name__, str(e)])
256            raise ApiException(status=0, reason=msg)
257
258        return RESTResponse(r)
RESTClientObject(configuration)
 63    def __init__(self, configuration) -> None:
 64        # urllib3.PoolManager will pass all kw parameters to connectionpool
 65        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75  # noqa: E501
 66        # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680  # noqa: E501
 67        # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html  # noqa: E501
 68
 69        # cert_reqs
 70        if configuration.verify_ssl:
 71            cert_reqs = ssl.CERT_REQUIRED
 72        else:
 73            cert_reqs = ssl.CERT_NONE
 74
 75        pool_args = {
 76            "cert_reqs": cert_reqs,
 77            "ca_certs": configuration.ssl_ca_cert,
 78            "cert_file": configuration.cert_file,
 79            "key_file": configuration.key_file,
 80        }
 81        if configuration.assert_hostname is not None:
 82            pool_args['assert_hostname'] = (
 83                configuration.assert_hostname
 84            )
 85
 86        if configuration.retries is not None:
 87            pool_args['retries'] = configuration.retries
 88
 89        if configuration.tls_server_name:
 90            pool_args['server_hostname'] = configuration.tls_server_name
 91
 92
 93        if configuration.socket_options is not None:
 94            pool_args['socket_options'] = configuration.socket_options
 95
 96        if configuration.connection_pool_maxsize is not None:
 97            pool_args['maxsize'] = configuration.connection_pool_maxsize
 98
 99        # https pool manager
100        self.pool_manager: urllib3.PoolManager
101
102        if configuration.proxy:
103            if is_socks_proxy_url(configuration.proxy):
104                from urllib3.contrib.socks import SOCKSProxyManager
105                pool_args["proxy_url"] = configuration.proxy
106                pool_args["headers"] = configuration.proxy_headers
107                self.pool_manager = SOCKSProxyManager(**pool_args)
108            else:
109                pool_args["proxy_url"] = configuration.proxy
110                pool_args["proxy_headers"] = configuration.proxy_headers
111                self.pool_manager = urllib3.ProxyManager(**pool_args)
112        else:
113            self.pool_manager = urllib3.PoolManager(**pool_args)
pool_manager: urllib3.poolmanager.PoolManager
def request( self, method, url, headers=None, body=None, post_params=None, _request_timeout=None):
115    def request(
116        self,
117        method,
118        url,
119        headers=None,
120        body=None,
121        post_params=None,
122        _request_timeout=None
123    ):
124        """Perform requests.
125
126        :param method: http request method
127        :param url: http request url
128        :param headers: http request headers
129        :param body: request json body, for `application/json`
130        :param post_params: request post parameters,
131                            `application/x-www-form-urlencoded`
132                            and `multipart/form-data`
133        :param _request_timeout: timeout setting for this request. If one
134                                 number provided, it will be total request
135                                 timeout. It can also be a pair (tuple) of
136                                 (connection, read) timeouts.
137        """
138        method = method.upper()
139        assert method in [
140            'GET',
141            'HEAD',
142            'DELETE',
143            'POST',
144            'PUT',
145            'PATCH',
146            'OPTIONS'
147        ]
148
149        if post_params and body:
150            raise ApiValueError(
151                "body parameter cannot be used with post_params parameter."
152            )
153
154        post_params = post_params or {}
155        headers = headers or {}
156
157        timeout = None
158        if _request_timeout:
159            if isinstance(_request_timeout, (int, float)):
160                timeout = urllib3.Timeout(total=_request_timeout)
161            elif (
162                    isinstance(_request_timeout, tuple)
163                    and len(_request_timeout) == 2
164                ):
165                timeout = urllib3.Timeout(
166                    connect=_request_timeout[0],
167                    read=_request_timeout[1]
168                )
169
170        try:
171            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
172            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
173
174                # no content type provided or payload is json
175                content_type = headers.get('Content-Type')
176                if (
177                    not content_type
178                    or re.search('json', content_type, re.IGNORECASE)
179                ):
180                    request_body = None
181                    if body is not None:
182                        request_body = json.dumps(body)
183                    r = self.pool_manager.request(
184                        method,
185                        url,
186                        body=request_body,
187                        timeout=timeout,
188                        headers=headers,
189                        preload_content=False
190                    )
191                elif content_type == 'application/x-www-form-urlencoded':
192                    r = self.pool_manager.request(
193                        method,
194                        url,
195                        fields=post_params,
196                        encode_multipart=False,
197                        timeout=timeout,
198                        headers=headers,
199                        preload_content=False
200                    )
201                elif content_type == 'multipart/form-data':
202                    # must del headers['Content-Type'], or the correct
203                    # Content-Type which generated by urllib3 will be
204                    # overwritten.
205                    del headers['Content-Type']
206                    # Ensures that dict objects are serialized
207                    post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
208                    r = self.pool_manager.request(
209                        method,
210                        url,
211                        fields=post_params,
212                        encode_multipart=True,
213                        timeout=timeout,
214                        headers=headers,
215                        preload_content=False
216                    )
217                # Pass a `string` parameter directly in the body to support
218                # other content types than JSON when `body` argument is
219                # provided in serialized form.
220                elif isinstance(body, str) or isinstance(body, bytes):
221                    r = self.pool_manager.request(
222                        method,
223                        url,
224                        body=body,
225                        timeout=timeout,
226                        headers=headers,
227                        preload_content=False
228                    )
229                elif headers['Content-Type'].startswith('text/') and isinstance(body, bool):
230                    request_body = "true" if body else "false"
231                    r = self.pool_manager.request(
232                        method,
233                        url,
234                        body=request_body,
235                        preload_content=False,
236                        timeout=timeout,
237                        headers=headers)
238                else:
239                    # Cannot generate the request from given parameters
240                    msg = """Cannot prepare a request message for provided
241                             arguments. Please check that your arguments match
242                             declared content type."""
243                    raise ApiException(status=0, reason=msg)
244            # For `GET`, `HEAD`
245            else:
246                r = self.pool_manager.request(
247                    method,
248                    url,
249                    fields={},
250                    timeout=timeout,
251                    headers=headers,
252                    preload_content=False
253                )
254        except urllib3.exceptions.SSLError as e:
255            msg = "\n".join([type(e).__name__, str(e)])
256            raise ApiException(status=0, reason=msg)
257
258        return RESTResponse(r)

Perform requests.

Parameters
  • method: http request method
  • url: http request url
  • headers: http request headers
  • body: request json body, for application/json
  • post_params: request post parameters, application/x-www-form-urlencoded and multipart/form-data
  • _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts.