コード例 #1
0
    def update_params_for_auth(self, headers, querys, auth_settings):
        """Updates header and query params based on authentication setting.

        :param headers: Header parameters dict to be updated.
        :param querys: Query parameters tuple list to be updated.
        :param auth_settings: Authentication setting identifiers list.
        """
        if not auth_settings:
            return

        for auth in auth_settings:
            auth_setting = self.configuration.auth_settings().get(auth)
            if auth_setting:
                if auth_setting['in'] == 'cookie':
                    headers['Cookie'] = auth_setting['value']
                elif auth_setting['in'] == 'header':
                    headers[auth_setting['key']] = auth_setting['value']
                elif auth_setting['in'] == 'query':
                    querys.append((auth_setting['key'], auth_setting['value']))
                else:
                    raise ApiValueError(
                        'Authentication token must be in `query` or `header`')
コード例 #2
0
    def create_token_review_with_http_info(self, body, **kwargs):  # noqa: E501
        """create_token_review  # noqa: E501

        create a TokenReview  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.create_token_review_with_http_info(body, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param V1TokenReview body: (required)
        :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
        :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
        :param str pretty: If 'true', then the output is pretty printed.
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _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.
        :return: tuple(V1TokenReview, status_code(int), headers(HTTPHeaderDict))
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = ['body', 'dry_run', 'field_manager', 'pretty']
        all_params.extend([
            'async_req', '_return_http_data_only', '_preload_content',
            '_request_timeout'
        ])

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError("Got an unexpected keyword argument '%s'"
                                   " to method create_token_review" % key)
            local_var_params[key] = val
        del local_var_params['kwargs']
        # verify the required parameter 'body' is set
        if self.api_client.client_side_validation and (
                'body' not in local_var_params or  # noqa: E501
                local_var_params['body'] is None):  # noqa: E501
            raise ApiValueError(
                "Missing the required parameter `body` when calling `create_token_review`"
            )  # noqa: E501

        collection_formats = {}

        path_params = {}

        query_params = []
        if 'dry_run' in local_var_params and local_var_params[
                'dry_run'] is not None:  # noqa: E501
            query_params.append(
                ('dryRun', local_var_params['dry_run']))  # noqa: E501
        if 'field_manager' in local_var_params and local_var_params[
                'field_manager'] is not None:  # noqa: E501
            query_params.append(
                ('fieldManager',
                 local_var_params['field_manager']))  # noqa: E501
        if 'pretty' in local_var_params and local_var_params[
                'pretty'] is not None:  # noqa: E501
            query_params.append(
                ('pretty', local_var_params['pretty']))  # noqa: E501

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        if 'body' in local_var_params:
            body_params = local_var_params['body']
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept([
            'application/json', 'application/yaml',
            'application/vnd.kubernetes.protobuf'
        ])  # noqa: E501

        # Authentication setting
        auth_settings = ['BearerToken']  # noqa: E501

        return self.api_client.call_api(
            '/apis/authentication.k8s.io/v1/tokenreviews',
            'POST',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type='V1TokenReview',  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get(
                '_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats)
コード例 #3
0
    def log_file_handler_with_http_info(self, logpath, **kwargs):  # noqa: E501
        """log_file_handler  # noqa: E501

        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.log_file_handler_with_http_info(logpath, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param str logpath: path to the log (required)
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _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.
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = ['logpath']
        all_params.extend([
            'async_req', '_return_http_data_only', '_preload_content',
            '_request_timeout'
        ])

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError("Got an unexpected keyword argument '%s'"
                                   " to method log_file_handler" % key)
            local_var_params[key] = val
        del local_var_params['kwargs']
        # verify the required parameter 'logpath' is set
        if self.api_client.client_side_validation and (
                'logpath' not in local_var_params or  # noqa: E501
                local_var_params['logpath'] is None):  # noqa: E501
            raise ApiValueError(
                "Missing the required parameter `logpath` when calling `log_file_handler`"
            )  # noqa: E501

        collection_formats = {}

        path_params = {}
        if 'logpath' in local_var_params:
            path_params['logpath'] = local_var_params['logpath']  # noqa: E501

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # Authentication setting
        auth_settings = ['BearerToken']  # noqa: E501

        return self.api_client.call_api(
            '/logs/{logpath}',
            'GET',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type=None,  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get(
                '_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats)
コード例 #4
0
 def request(self,
             method,
             url,
             query_params=None,
             headers=None,
             post_params=None,
             body=None,
             _preload_content=True,
             _request_timeout=None):
     """Makes the HTTP request using RESTClient."""
     if method == "GET":
         return self.rest_client.GET(url,
                                     query_params=query_params,
                                     _preload_content=_preload_content,
                                     _request_timeout=_request_timeout,
                                     headers=headers)
     elif method == "HEAD":
         return self.rest_client.HEAD(url,
                                      query_params=query_params,
                                      _preload_content=_preload_content,
                                      _request_timeout=_request_timeout,
                                      headers=headers)
     elif method == "OPTIONS":
         return self.rest_client.OPTIONS(url,
                                         query_params=query_params,
                                         headers=headers,
                                         _preload_content=_preload_content,
                                         _request_timeout=_request_timeout)
     elif method == "POST":
         return self.rest_client.POST(url,
                                      query_params=query_params,
                                      headers=headers,
                                      post_params=post_params,
                                      _preload_content=_preload_content,
                                      _request_timeout=_request_timeout,
                                      body=body)
     elif method == "PUT":
         return self.rest_client.PUT(url,
                                     query_params=query_params,
                                     headers=headers,
                                     post_params=post_params,
                                     _preload_content=_preload_content,
                                     _request_timeout=_request_timeout,
                                     body=body)
     elif method == "PATCH":
         return self.rest_client.PATCH(url,
                                       query_params=query_params,
                                       headers=headers,
                                       post_params=post_params,
                                       _preload_content=_preload_content,
                                       _request_timeout=_request_timeout,
                                       body=body)
     elif method == "DELETE":
         return self.rest_client.DELETE(url,
                                        query_params=query_params,
                                        headers=headers,
                                        _preload_content=_preload_content,
                                        _request_timeout=_request_timeout,
                                        body=body)
     else:
         raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`,"
                             " `POST`, `PATCH`, `PUT` or `DELETE`.")
コード例 #5
0
    async def request(self, method, url, query_params=None, headers=None,
                      body=None, post_params=None, _preload_content=True,
                      _request_timeout=None):
        """Execute request

        :param method: http request method
        :param url: http request url
        :param query_params: query parameters in the url
        :param headers: http request headers
        :param body: request json body, for `application/json`
        :param post_params: request post parameters,
                            `application/x-www-form-urlencoded`
                            and `multipart/form-data`
        :param _preload_content: this is a non-applicable field for
                                 the AiohttpClient.
        :param _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.
        """
        method = method.upper()
        assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT',
                          'PATCH', 'OPTIONS']

        if post_params and body:
            raise ApiValueError(
                "body parameter cannot be used with post_params parameter."
            )

        post_params = post_params or {}
        headers = headers or {}
        timeout = _request_timeout or 5 * 60

        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

        args = {
            "method": method,
            "url": url,
            "timeout": timeout,
            "headers": headers
        }

        if query_params:
            args["url"] += '?' + urlencode(query_params)

        # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
        if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
            if re.search('json', headers['Content-Type'], re.IGNORECASE):
                if headers['Content-Type'] == 'application/json-patch+json':
                    if not isinstance(body, list):
                        headers['Content-Type'] = 'application/strategic-merge-patch+json'
                if body is not None:
                    body = json.dumps(body)
                args["data"] = body
            elif headers['Content-Type'] == 'application/x-www-form-urlencoded':  # noqa: E501
                args["data"] = aiohttp.FormData(post_params)
            elif headers['Content-Type'] == 'multipart/form-data':
                # must del headers['Content-Type'], or the correct
                # Content-Type which generated by aiohttp
                del headers['Content-Type']
                data = aiohttp.FormData()
                for param in post_params:
                    k, v = param
                    if isinstance(v, tuple) and len(v) == 3:
                        data.add_field(k,
                                       value=v[1],
                                       filename=v[0],
                                       content_type=v[2])
                    else:
                        data.add_field(k, v)
                args["data"] = data

            # Pass a `bytes` parameter directly in the body to support
            # other content types than Json when `body` argument is provided
            # in serialized form
            elif isinstance(body, bytes):
                args["data"] = body
            else:
                # Cannot generate the request from given parameters
                msg = """Cannot prepare a request message for provided
                         arguments. Please check that your arguments match
                         declared content type."""
                raise ApiException(status=0, reason=msg)

        r = await self.pool_manager.request(**args)
        if _preload_content:

            data = await r.text()
            r = RESTResponse(r, data)

            # log response body
            logger.debug("response body: %s", r.data)

            if not 200 <= r.status <= 299:
                raise ApiException(http_resp=r)

        return r