Ejemplo n.º 1
0
 def __init__(
     self,
     config: rpc_models.Config,
 ):
     """
     Init client with Config
     @param config: config contains the necessary information to create a client
     """
     if UtilClient.is_unset(config):
         raise TeaException({
             'code': 'ParameterMissing',
             'message': "'config' can not be unset"
         })
     UtilClient.validate_model(config)
     if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(
             config.access_key_secret):
         if not UtilClient.empty(config.security_token):
             config.type = 'sts'
         else:
             config.type = 'access_key'
         credential_config = credential_models.Config(
             access_key_id=config.access_key_id,
             type=config.type,
             access_key_secret=config.access_key_secret,
             security_token=config.security_token)
         self._credential = CredentialClient(credential_config)
     elif not UtilClient.is_unset(config.credential):
         self._credential = config.credential
     else:
         raise TeaException({
             'code':
             'ParameterMissing',
             'message':
             "'accessKeyId' and 'accessKeySecret' or 'credential' can not be unset"
         })
     self._network = config.network
     self._suffix = config.suffix
     self._endpoint = config.endpoint
     self._protocol = config.protocol
     self._region_id = config.region_id
     self._user_agent = config.user_agent
     self._read_timeout = config.read_timeout
     self._connect_timeout = config.connect_timeout
     self._http_proxy = config.http_proxy
     self._https_proxy = config.https_proxy
     self._no_proxy = config.no_proxy
     self._socks_5proxy = config.socks_5proxy
     self._socks_5net_work = config.socks_5net_work
     self._max_idle_conns = config.max_idle_conns
     self._endpoint_type = config.endpoint_type
     self._open_platform_endpoint = config.open_platform_endpoint
Ejemplo n.º 2
0
 def __init__(
     self,
     config: open_search_models.Config,
 ):
     if UtilClient.is_unset(config):
         raise TeaException({
             'name': 'ParameterMissing',
             'message': "'config' can not be unset"
         })
     if UtilClient.empty(config.type):
         config.type = 'access_key'
     credential_config = credential_models.Config(
         access_key_id=config.access_key_id,
         type=config.type,
         access_key_secret=config.access_key_secret,
         security_token=config.security_token)
     self._credential = CredentialClient(credential_config)
     self._endpoint = config.endpoint
     self._protocol = config.protocol
     self._user_agent = config.user_agent
Ejemplo n.º 3
0
    def test_ak_client(self):
        conf = Config()
        conf.type = auth_constant.ACCESS_KEY
        conf.access_key_id = '123456'
        conf.access_key_secret = '654321'
        cred = Client(conf)
        self.assertEqual('123456', cred.get_access_key_id())
        self.assertEqual('654321', cred.get_access_key_secret())
        self.assertEqual(auth_constant.ACCESS_KEY, cred.get_type())
        self.assertIsNone(cred.get_security_token())
        try:
            cred = Client()
            cred.get_access_key_id()
        except Exception as e:
            self.assertEqual('not found credentials', str(e))

        conf = Config(type='sts')
        cred = Client(conf)
        self.assertIsInstance(cred.cloud_credential, credentials.StsCredential)

        conf = Config(type='bearer')
        cred = Client(conf)
        self.assertIsInstance(cred.cloud_credential,
                              credentials.BearerTokenCredential)

        conf = Config(type='ecs_ram_role')
        self.assertIsInstance(Client.get_credential(conf),
                              credentials.EcsRamRoleCredential)

        conf = Config(type='ram_role_arn')
        self.assertIsInstance(Client.get_credential(conf),
                              credentials.RamRoleArnCredential)

        conf = Config(type='rsa_key_pair')
        self.assertIsInstance(Client.get_credential(conf),
                              credentials.RsaKeyPairCredential)

        conf = Config(access_key_id='ak1',
                      access_key_secret='sk1',
                      type='access_key')
        client = Client(conf)
        loop = asyncio.get_event_loop()
        task = asyncio.ensure_future(client.get_security_token_async())
        loop.run_until_complete(task)
        self.assertIsNone(task.result())
        task = asyncio.ensure_future(client.get_access_key_id_async())
        loop.run_until_complete(task)
        self.assertEqual('ak1', task.result())
        task = asyncio.ensure_future(client.get_access_key_secret_async())
        loop.run_until_complete(task)
        self.assertEqual('sk1', task.result())
Ejemplo n.º 4
0
class Client(object):
    """
    This is for OpenApi SDK
    """
    _endpoint = None  # type: str
    _region_id = None  # type: str
    _protocol = None  # type: str
    _method = None  # type: str
    _user_agent = None  # type: str
    _endpoint_rule = None  # type: str
    _endpoint_map = None  # type: dict[str, str]
    _suffix = None  # type: str
    _read_timeout = None  # type: int
    _connect_timeout = None  # type: int
    _http_proxy = None  # type: str
    _https_proxy = None  # type: str
    _socks_5proxy = None  # type: str
    _socks_5net_work = None  # type: str
    _no_proxy = None  # type: str
    _network = None  # type: str
    _product_id = None  # type: str
    _max_idle_conns = None  # type: int
    _endpoint_type = None  # type: str
    _open_platform_endpoint = None  # type: str
    _credential = None  # type: CredentialClient
    _signature_version = None  # type: str
    _signature_algorithm = None  # type: str
    _headers = None  # type: dict[str, str]
    _spi = None  # type: SPIClient

    def __init__(self, config):
        """
        Init client with Config

        @param config: config contains the necessary information to create a client
        """
        if UtilClient.is_unset(config):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config' can not be unset"
            })
        if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(config.access_key_secret):
            if not UtilClient.empty(config.security_token):
                config.type = 'sts'
            else:
                config.type = 'access_key'
            credential_config = credential_models.Config(
                access_key_id=config.access_key_id,
                type=config.type,
                access_key_secret=config.access_key_secret,
                security_token=config.security_token
            )
            self._credential = CredentialClient(credential_config)
        elif not UtilClient.is_unset(config.credential):
            self._credential = config.credential
        self._endpoint = config.endpoint
        self._endpoint_type = config.endpoint_type
        self._network = config.network
        self._suffix = config.suffix
        self._protocol = config.protocol
        self._method = config.method
        self._region_id = config.region_id
        self._user_agent = config.user_agent
        self._read_timeout = config.read_timeout
        self._connect_timeout = config.connect_timeout
        self._http_proxy = config.http_proxy
        self._https_proxy = config.https_proxy
        self._no_proxy = config.no_proxy
        self._socks_5proxy = config.socks_5proxy
        self._socks_5net_work = config.socks_5net_work
        self._max_idle_conns = config.max_idle_conns
        self._signature_version = config.signature_version
        self._signature_algorithm = config.signature_algorithm

    def do_rpcrequest(self, action, version, protocol, method, auth_type, body_type, request, runtime):
        """
        Encapsulate the request and invoke the network

        @type action: str
        @param action: api name

        @type version: str
        @param version: product version

        @type protocol: str
        @param protocol: http or https

        @type method: str
        @param method: e.g. GET

        @type auth_type: str
        @param auth_type: authorization type e.g. AK

        @type body_type: str
        @param body_type: response body type e.g. String

        @param request: object of OpenApiRequest

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'socks5Proxy': UtilClient.default_string(runtime.socks_5proxy, self._socks_5proxy),
            'socks5NetWork': UtilClient.default_string(runtime.socks_5net_work, self._socks_5net_work),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, protocol)
                _request.method = method
                _request.pathname = '/'
                _request.query = TeaCore.merge({
                    'Action': action,
                    'Format': 'json',
                    'Version': version,
                    'Timestamp': OpenApiUtilClient.get_timestamp(),
                    'SignatureNonce': UtilClient.get_nonce()
                }, request.query)
                headers = self.get_rpc_headers()
                if UtilClient.is_unset(headers):
                    # endpoint is setted in product client
                    _request.headers = {
                        'host': self._endpoint,
                        'x-acs-version': version,
                        'x-acs-action': action,
                        'user-agent': self.get_user_agent()
                    }
                else:
                    _request.headers = TeaCore.merge({
                        'host': self._endpoint,
                        'x-acs-version': version,
                        'x-acs-action': action,
                        'user-agent': self.get_user_agent()
                    }, headers)
                if not UtilClient.is_unset(request.body):
                    m = UtilClient.assert_as_map(request.body)
                    tmp = UtilClient.anyify_map_value(OpenApiUtilClient.query(m))
                    _request.body = UtilClient.to_form_string(tmp)
                    _request.headers['content-type'] = 'application/x-www-form-urlencoded'
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self.get_access_key_id()
                    access_key_secret = self.get_access_key_secret()
                    security_token = self.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.query['SecurityToken'] = security_token
                    _request.query['SignatureMethod'] = 'HMAC-SHA1'
                    _request.query['SignatureVersion'] = '1.0'
                    _request.query['AccessKeyId'] = access_key_id
                    t = None
                    if not UtilClient.is_unset(request.body):
                        t = UtilClient.assert_as_map(request.body)
                    signed_param = TeaCore.merge(_request.query,
                        OpenApiUtilClient.query(t))
                    _request.query['Signature'] = OpenApiUtilClient.get_rpcsignature(signed_param, _request.method, access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.is_4xx(_response.status_code) or UtilClient.is_5xx(_response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    request_id = self.default_any(err.get('RequestId'), err.get('requestId'))
                    raise TeaException({
                        'code': '%s' % TeaConverter.to_unicode(self.default_any(err.get('Code'), err.get('code'))),
                        'message': 'code: %s, %s request id: %s' % (TeaConverter.to_unicode(_response.status_code), TeaConverter.to_unicode(self.default_any(err.get('Message'), err.get('message'))), TeaConverter.to_unicode(request_id)),
                        'data': err
                    })
                if UtilClient.equal_string(body_type, 'binary'):
                    resp = {
                        'body': _response.body,
                        'headers': _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, 'byte'):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {
                        'body': byt,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'string'):
                    str = UtilClient.read_as_string(_response.body)
                    return {
                        'body': str,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'json'):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {
                        'body': res,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'array'):
                    arr = UtilClient.read_as_json(_response.body)
                    return {
                        'body': arr,
                        'headers': _response.headers
                    }
                else:
                    return {
                        'headers': _response.headers
                    }
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_roarequest(self, action, version, protocol, method, auth_type, pathname, body_type, request, runtime):
        """
        Encapsulate the request and invoke the network

        @type action: str
        @param action: api name

        @type version: str
        @param version: product version

        @type protocol: str
        @param protocol: http or https

        @type method: str
        @param method: e.g. GET

        @type auth_type: str
        @param auth_type: authorization type e.g. AK

        @type pathname: str
        @param pathname: pathname of every api

        @type body_type: str
        @param body_type: response body type e.g. String

        @param request: object of OpenApiRequest

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'socks5Proxy': UtilClient.default_string(runtime.socks_5proxy, self._socks_5proxy),
            'socks5NetWork': UtilClient.default_string(runtime.socks_5net_work, self._socks_5net_work),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge({
                    'date': UtilClient.get_date_utcstring(),
                    'host': self._endpoint,
                    'accept': 'application/json',
                    'x-acs-signature-nonce': UtilClient.get_nonce(),
                    'x-acs-signature-method': 'HMAC-SHA1',
                    'x-acs-signature-version': '1.0',
                    'x-acs-version': version,
                    'x-acs-action': action,
                    'user-agent': UtilClient.get_user_agent(self._user_agent)
                }, request.headers)
                if not UtilClient.is_unset(request.body):
                    _request.body = UtilClient.to_jsonstring(request.body)
                    _request.headers['content-type'] = 'application/json; charset=utf-8'
                if not UtilClient.is_unset(request.query):
                    _request.query = request.query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self.get_access_key_id()
                    access_key_secret = self.get_access_key_secret()
                    security_token = self.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers['x-acs-security-token'] = security_token
                    string_to_sign = OpenApiUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (TeaConverter.to_unicode(access_key_id), TeaConverter.to_unicode(OpenApiUtilClient.get_roasignature(string_to_sign, access_key_secret)))
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {
                        'headers': _response.headers
                    }
                if UtilClient.is_4xx(_response.status_code) or UtilClient.is_5xx(_response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    request_id = self.default_any(err.get('RequestId'), err.get('requestId'))
                    request_id = self.default_any(request_id, err.get('requestid'))
                    raise TeaException({
                        'code': '%s' % TeaConverter.to_unicode(self.default_any(err.get('Code'), err.get('code'))),
                        'message': 'code: %s, %s request id: %s' % (TeaConverter.to_unicode(_response.status_code), TeaConverter.to_unicode(self.default_any(err.get('Message'), err.get('message'))), TeaConverter.to_unicode(request_id)),
                        'data': err
                    })
                if UtilClient.equal_string(body_type, 'binary'):
                    resp = {
                        'body': _response.body,
                        'headers': _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, 'byte'):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {
                        'body': byt,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'string'):
                    str = UtilClient.read_as_string(_response.body)
                    return {
                        'body': str,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'json'):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {
                        'body': res,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'array'):
                    arr = UtilClient.read_as_json(_response.body)
                    return {
                        'body': arr,
                        'headers': _response.headers
                    }
                else:
                    return {
                        'headers': _response.headers
                    }
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_roarequest_with_form(self, action, version, protocol, method, auth_type, pathname, body_type, request, runtime):
        """
        Encapsulate the request and invoke the network with form body

        @type action: str
        @param action: api name

        @type version: str
        @param version: product version

        @type protocol: str
        @param protocol: http or https

        @type method: str
        @param method: e.g. GET

        @type auth_type: str
        @param auth_type: authorization type e.g. AK

        @type pathname: str
        @param pathname: pathname of every api

        @type body_type: str
        @param body_type: response body type e.g. String

        @param request: object of OpenApiRequest

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'socks5Proxy': UtilClient.default_string(runtime.socks_5proxy, self._socks_5proxy),
            'socks5NetWork': UtilClient.default_string(runtime.socks_5net_work, self._socks_5net_work),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge({
                    'date': UtilClient.get_date_utcstring(),
                    'host': self._endpoint,
                    'accept': 'application/json',
                    'x-acs-signature-nonce': UtilClient.get_nonce(),
                    'x-acs-signature-method': 'HMAC-SHA1',
                    'x-acs-signature-version': '1.0',
                    'x-acs-version': version,
                    'x-acs-action': action,
                    'user-agent': UtilClient.get_user_agent(self._user_agent)
                }, request.headers)
                if not UtilClient.is_unset(request.body):
                    m = UtilClient.assert_as_map(request.body)
                    _request.body = OpenApiUtilClient.to_form(m)
                    _request.headers['content-type'] = 'application/x-www-form-urlencoded'
                if not UtilClient.is_unset(request.query):
                    _request.query = request.query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self.get_access_key_id()
                    access_key_secret = self.get_access_key_secret()
                    security_token = self.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers['x-acs-security-token'] = security_token
                    string_to_sign = OpenApiUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (TeaConverter.to_unicode(access_key_id), TeaConverter.to_unicode(OpenApiUtilClient.get_roasignature(string_to_sign, access_key_secret)))
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {
                        'headers': _response.headers
                    }
                if UtilClient.is_4xx(_response.status_code) or UtilClient.is_5xx(_response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    raise TeaException({
                        'code': '%s' % TeaConverter.to_unicode(self.default_any(err.get('Code'), err.get('code'))),
                        'message': 'code: %s, %s request id: %s' % (TeaConverter.to_unicode(_response.status_code), TeaConverter.to_unicode(self.default_any(err.get('Message'), err.get('message'))), TeaConverter.to_unicode(self.default_any(err.get('RequestId'), err.get('requestId')))),
                        'data': err
                    })
                if UtilClient.equal_string(body_type, 'binary'):
                    resp = {
                        'body': _response.body,
                        'headers': _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, 'byte'):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {
                        'body': byt,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'string'):
                    str = UtilClient.read_as_string(_response.body)
                    return {
                        'body': str,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'json'):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {
                        'body': res,
                        'headers': _response.headers
                    }
                elif UtilClient.equal_string(body_type, 'array'):
                    arr = UtilClient.read_as_json(_response.body)
                    return {
                        'body': arr,
                        'headers': _response.headers
                    }
                else:
                    return {
                        'headers': _response.headers
                    }
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_request(self, params, request, runtime):
        """
        Encapsulate the request and invoke the network

        @param action: api name

        @param version: product version

        @param protocol: http or https

        @param method: e.g. GET

        @param auth_type: authorization type e.g. AK

        @param body_type: response body type e.g. String

        @param request: object of OpenApiRequest

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        params.validate()
        request.validate()
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'socks5Proxy': UtilClient.default_string(runtime.socks_5proxy, self._socks_5proxy),
            'socks5NetWork': UtilClient.default_string(runtime.socks_5net_work, self._socks_5net_work),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, params.protocol)
                _request.method = params.method
                _request.pathname = params.pathname
                _request.query = request.query
                # endpoint is setted in product client
                _request.headers = TeaCore.merge({
                    'host': self._endpoint,
                    'x-acs-version': params.version,
                    'x-acs-action': params.action,
                    'user-agent': self.get_user_agent(),
                    'x-acs-date': OpenApiUtilClient.get_timestamp(),
                    'x-acs-signature-nonce': UtilClient.get_nonce(),
                    'accept': 'application/json'
                }, request.headers)
                if UtilClient.equal_string(params.style, 'RPC'):
                    headers = self.get_rpc_headers()
                    if not UtilClient.is_unset(headers):
                        _request.headers = TeaCore.merge(_request.headers,
                            headers)
                signature_algorithm = UtilClient.default_string(self._signature_algorithm, 'ACS3-HMAC-SHA256')
                hashed_request_payload = OpenApiUtilClient.hex_encode(OpenApiUtilClient.hash(UtilClient.to_bytes(''), signature_algorithm))
                if not UtilClient.is_unset(request.stream):
                    tmp = UtilClient.read_as_bytes(request.stream)
                    hashed_request_payload = OpenApiUtilClient.hex_encode(OpenApiUtilClient.hash(tmp, signature_algorithm))
                    _request.body = tmp
                    _request.headers['content-type'] = 'application/octet-stream'
                else:
                    if not UtilClient.is_unset(request.body):
                        if UtilClient.equal_string(params.req_body_type, 'json'):
                            json_obj = UtilClient.to_jsonstring(request.body)
                            hashed_request_payload = OpenApiUtilClient.hex_encode(OpenApiUtilClient.hash(UtilClient.to_bytes(json_obj), signature_algorithm))
                            _request.body = json_obj
                            _request.headers['content-type'] = 'application/json; charset=utf-8'
                        else:
                            m = UtilClient.assert_as_map(request.body)
                            form_obj = OpenApiUtilClient.to_form(m)
                            hashed_request_payload = OpenApiUtilClient.hex_encode(OpenApiUtilClient.hash(UtilClient.to_bytes(form_obj), signature_algorithm))
                            _request.body = form_obj
                            _request.headers['content-type'] = 'application/x-www-form-urlencoded'
                _request.headers['x-acs-content-sha256'] = hashed_request_payload
                if not UtilClient.equal_string(params.auth_type, 'Anonymous'):
                    auth_type = self.get_type()
                    if UtilClient.equal_string(auth_type, 'bearer'):
                        bearer_token = self.get_bearer_token()
                        _request.headers['x-acs-bearer-token'] = bearer_token
                    else:
                        access_key_id = self.get_access_key_id()
                        access_key_secret = self.get_access_key_secret()
                        security_token = self.get_security_token()
                        if not UtilClient.empty(security_token):
                            _request.headers['x-acs-accesskey-id'] = access_key_id
                            _request.headers['x-acs-security-token'] = security_token
                        _request.headers['Authorization'] = OpenApiUtilClient.get_authorization(_request, signature_algorithm, hashed_request_payload, access_key_id, access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.is_4xx(_response.status_code) or UtilClient.is_5xx(_response.status_code):
                    err = {}
                    if not UtilClient.is_unset(_response.headers.get('content-type')) and UtilClient.equal_string(_response.headers.get('content-type'), 'text/xml;charset=utf-8'):
                        _str = UtilClient.read_as_string(_response.body)
                        resp_map = XMLClient.parse_xml(_str, None)
                        err = UtilClient.assert_as_map(resp_map.get('Error'))
                    else:
                        _res = UtilClient.read_as_json(_response.body)
                        err = UtilClient.assert_as_map(_res)
                    err['statusCode'] = _response.status_code
                    raise TeaException({
                        'code': '%s' % TeaConverter.to_unicode(self.default_any(err.get('Code'), err.get('code'))),
                        'message': 'code: %s, %s request id: %s' % (TeaConverter.to_unicode(_response.status_code), TeaConverter.to_unicode(self.default_any(err.get('Message'), err.get('message'))), TeaConverter.to_unicode(self.default_any(err.get('RequestId'), err.get('requestId')))),
                        'data': err
                    })
                if UtilClient.equal_string(params.body_type, 'binary'):
                    resp = {
                        'body': _response.body,
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
                    return resp
                elif UtilClient.equal_string(params.body_type, 'byte'):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {
                        'body': byt,
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
                elif UtilClient.equal_string(params.body_type, 'string'):
                    str = UtilClient.read_as_string(_response.body)
                    return {
                        'body': str,
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
                elif UtilClient.equal_string(params.body_type, 'json'):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {
                        'body': res,
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
                elif UtilClient.equal_string(params.body_type, 'array'):
                    arr = UtilClient.read_as_json(_response.body)
                    return {
                        'body': arr,
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
                else:
                    return {
                        'headers': _response.headers,
                        'statusCode': _response.status_code
                    }
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def execute(self, params, request, runtime):
        """
        Encapsulate the request and invoke the network

        @param action: api name

        @param version: product version

        @param protocol: http or https

        @param method: e.g. GET

        @param auth_type: authorization type e.g. AK

        @param body_type: response body type e.g. String

        @param request: object of OpenApiRequest

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        params.validate()
        request.validate()
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'socks5Proxy': UtilClient.default_string(runtime.socks_5proxy, self._socks_5proxy),
            'socks5NetWork': UtilClient.default_string(runtime.socks_5net_work, self._socks_5net_work),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                # spi = new Gateway();//Gateway implements SPI,这一步在产品 SDK 中实例化
                headers = self.get_rpc_headers()
                request_context = spi_models.InterceptorContextRequest(
                    headers=TeaCore.merge(request.headers,
                        headers),
                    query=request.query,
                    body=request.body,
                    stream=request.stream,
                    host_map=request.host_map,
                    pathname=params.pathname,
                    product_id=self._product_id,
                    action=params.action,
                    version=params.version,
                    protocol=UtilClient.default_string(self._protocol, params.protocol),
                    method=UtilClient.default_string(self._method, params.method),
                    auth_type=params.auth_type,
                    body_type=params.body_type,
                    req_body_type=params.req_body_type,
                    style=params.style,
                    credential=self._credential,
                    signature_version=self._signature_version,
                    signature_algorithm=self._signature_algorithm,
                    user_agent=self.get_user_agent()
                )
                configuration_context = spi_models.InterceptorContextConfiguration(
                    region_id=self._region_id,
                    endpoint=UtilClient.default_string(request.endpoint_override, self._endpoint),
                    endpoint_rule=self._endpoint_rule,
                    endpoint_map=self._endpoint_map,
                    endpoint_type=self._endpoint_type,
                    network=self._network,
                    suffix=self._suffix
                )
                interceptor_context = spi_models.InterceptorContext(
                    request=request_context,
                    configuration=configuration_context
                )
                attribute_map = spi_models.AttributeMap()
                # 1. spi.modifyConfiguration(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap);
                self._spi.modify_configuration(interceptor_context, attribute_map)
                # 2. spi.modifyRequest(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap);
                self._spi.modify_request(interceptor_context, attribute_map)
                _request.protocol = interceptor_context.request.protocol
                _request.method = interceptor_context.request.method
                _request.pathname = interceptor_context.request.pathname
                _request.query = interceptor_context.request.query
                _request.body = interceptor_context.request.stream
                _request.headers = interceptor_context.request.headers
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                response_context = spi_models.InterceptorContextResponse(
                    status_code=_response.status_code,
                    headers=_response.headers,
                    body=_response.body
                )
                interceptor_context.response = response_context
                # 3. spi.modifyResponse(context: SPI.InterceptorContext, attributeMap: SPI.AttributeMap);
                self._spi.modify_response(interceptor_context, attribute_map)
                return {
                    'headers': interceptor_context.response.headers,
                    'statusCode': interceptor_context.response.status_code,
                    'body': interceptor_context.response.deserialized_body
                }
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def call_api(self, params, request, runtime):
        if UtilClient.is_unset(params):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'params' can not be unset"
            })
        if UtilClient.is_unset(self._signature_algorithm) or not UtilClient.equal_string(self._signature_algorithm, 'v2'):
            return self.do_request(params, request, runtime)
        elif UtilClient.equal_string(params.style, 'ROA') and UtilClient.equal_string(params.req_body_type, 'json'):
            return self.do_roarequest(params.action, params.version, params.protocol, params.method, params.auth_type, params.pathname, params.body_type, request, runtime)
        elif UtilClient.equal_string(params.style, 'ROA'):
            return self.do_roarequest_with_form(params.action, params.version, params.protocol, params.method, params.auth_type, params.pathname, params.body_type, request, runtime)
        else:
            return self.do_rpcrequest(params.action, params.version, params.protocol, params.method, params.auth_type, params.body_type, request, runtime)

    def get_user_agent(self):
        """
        Get user agent

        @rtype: str
        @return: user agent
        """
        user_agent = UtilClient.get_user_agent(self._user_agent)
        return user_agent

    def get_access_key_id(self):
        """
        Get accesskey id by using credential

        @rtype: str
        @return: accesskey id
        """
        if UtilClient.is_unset(self._credential):
            return ''
        access_key_id = self._credential.get_access_key_id()
        return access_key_id

    def get_access_key_secret(self):
        """
        Get accesskey secret by using credential

        @rtype: str
        @return: accesskey secret
        """
        if UtilClient.is_unset(self._credential):
            return ''
        secret = self._credential.get_access_key_secret()
        return secret

    def get_security_token(self):
        """
        Get security token by using credential

        @rtype: str
        @return: security token
        """
        if UtilClient.is_unset(self._credential):
            return ''
        token = self._credential.get_security_token()
        return token

    def get_bearer_token(self):
        """
        Get bearer token by credential

        @rtype: str
        @return: bearer token
        """
        if UtilClient.is_unset(self._credential):
            return ''
        token = self._credential.get_bearer_token()
        return token

    def get_type(self):
        """
        Get credential type by credential

        @rtype: str
        @return: credential type e.g. access_key
        """
        if UtilClient.is_unset(self._credential):
            return ''
        auth_type = self._credential.get_type()
        return auth_type

    @staticmethod
    def default_any(input_value, default_value):
        """
        If inputValue is not null, return it or return defaultValue

        @param input_value:  users input value

        @param default_value: default value

        @return: the final result
        """
        if UtilClient.is_unset(input_value):
            return default_value
        return input_value

    def check_config(self, config):
        """
        If the endpointRule and config.endpoint are empty, throw error

        @param config: config contains the necessary information to create a client
        """
        if UtilClient.empty(self._endpoint_rule) and UtilClient.empty(config.endpoint):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config.endpoint' can not be empty"
            })

    def set_rpc_headers(self, headers):
        """
        set RPC header for debug

        @type headers: dict
        @param headers: headers for debug, this header can be used only once.
        """
        self._headers = headers

    def get_rpc_headers(self):
        """
        get RPC header for debug
        """
        headers = self._headers
        self._headers = None
        return headers
Ejemplo n.º 5
0
class Client:
    """
    *\
    """
    _endpoint: str = None
    _protocol: str = None
    _user_agent: str = None
    _credential: CredentialClient = None

    def __init__(
        self,
        config: open_search_models.Config,
    ):
        if UtilClient.is_unset(config):
            raise TeaException({
                'name': 'ParameterMissing',
                'message': "'config' can not be unset"
            })
        if UtilClient.empty(config.type):
            config.type = 'access_key'
        credential_config = credential_models.Config(
            access_key_id=config.access_key_id,
            type=config.type,
            access_key_secret=config.access_key_secret,
            security_token=config.security_token)
        self._credential = CredentialClient(credential_config)
        self._endpoint = config.endpoint
        self._protocol = config.protocol
        self._user_agent = config.user_agent

    def _request(
        self,
        method: str,
        pathname: str,
        query: Dict[str, Any],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> Dict[str, Any]:
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': runtime.read_timeout,
            'connectTimeout': runtime.connect_timeout,
            'httpProxy': runtime.http_proxy,
            'httpsProxy': runtime.https_proxy,
            'noProxy': runtime.no_proxy,
            'maxIdleConns': runtime.max_idle_conns,
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                accesskey_id = self.get_access_key_id()
                access_key_secret = self.get_access_key_secret()
                _request.protocol = UtilClient.default_string(
                    self._protocol, 'HTTP')
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'user-agent':
                        self.get_user_agent(),
                        'Date':
                        OpensearchUtil.get_date(),
                        'host':
                        UtilClient.default_string(
                            self._endpoint,
                            f'opensearch-cn-hangzhou.aliyuncs.com'),
                        'X-Opensearch-Nonce':
                        UtilClient.get_nonce()
                    }, headers)
                if not UtilClient.is_unset(query):
                    _request.query = UtilClient.stringify_map_value(query)
                if not UtilClient.is_unset(body):
                    req_body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'Content-MD5'] = OpensearchUtil.get_content_md5(
                            req_body)
                    _request.headers['Content-Type'] = 'application/json'
                    _request.body = req_body
                _request.headers[
                    'Authorization'] = OpensearchUtil.get_signature(
                        _request, accesskey_id, access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                obj_str = UtilClient.read_as_string(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    raise TeaException({
                        'message': _response.status_message,
                        'data': obj_str,
                        'code': _response.status_code
                    })
                obj = UtilClient.parse_json(obj_str)
                res = UtilClient.assert_as_map(obj)
                return {'body': res, 'headers': _response.headers}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    async def _request_async(
        self,
        method: str,
        pathname: str,
        query: Dict[str, Any],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> Dict[str, Any]:
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': runtime.read_timeout,
            'connectTimeout': runtime.connect_timeout,
            'httpProxy': runtime.http_proxy,
            'httpsProxy': runtime.https_proxy,
            'noProxy': runtime.no_proxy,
            'maxIdleConns': runtime.max_idle_conns,
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                accesskey_id = await self.get_access_key_id_async()
                access_key_secret = await self.get_access_key_secret_async()
                _request.protocol = UtilClient.default_string(
                    self._protocol, 'HTTP')
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'user-agent':
                        self.get_user_agent(),
                        'Date':
                        OpensearchUtil.get_date(),
                        'host':
                        UtilClient.default_string(
                            self._endpoint,
                            f'opensearch-cn-hangzhou.aliyuncs.com'),
                        'X-Opensearch-Nonce':
                        UtilClient.get_nonce()
                    }, headers)
                if not UtilClient.is_unset(query):
                    _request.query = UtilClient.stringify_map_value(query)
                if not UtilClient.is_unset(body):
                    req_body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'Content-MD5'] = OpensearchUtil.get_content_md5(
                            req_body)
                    _request.headers['Content-Type'] = 'application/json'
                    _request.body = req_body
                _request.headers[
                    'Authorization'] = OpensearchUtil.get_signature(
                        _request, accesskey_id, access_key_secret)
                _last_request = _request
                _response = await TeaCore.async_do_action(_request, _runtime)
                obj_str = await UtilClient.read_as_string_async(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    raise TeaException({
                        'message': _response.status_message,
                        'data': obj_str,
                        'code': _response.status_code
                    })
                obj = UtilClient.parse_json(obj_str)
                res = UtilClient.assert_as_map(obj)
                return {'body': res, 'headers': _response.headers}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def search_ex(
        self,
        app_name: str,
        request: open_search_models.SearchRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.SearchResponseModel:
        """
        系统提供了丰富的搜索语法以满足用户各种场景下的搜索需求。
        """
        return TeaCore.from_map(
            open_search_models.SearchResponseModel(),
            self._request('GET', f'/v3/openapi/apps/{app_name}/search',
                          TeaCore.to_map(request.query), request.headers, None,
                          runtime))

    async def search_ex_async(
        self,
        app_name: str,
        request: open_search_models.SearchRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.SearchResponseModel:
        """
        系统提供了丰富的搜索语法以满足用户各种场景下的搜索需求。
        """
        return TeaCore.from_map(
            open_search_models.SearchResponseModel(), await
            self._request_async('GET', f'/v3/openapi/apps/{app_name}/search',
                                TeaCore.to_map(request.query), request.headers,
                                None, runtime))

    def search(
        self,
        app_name: str,
        request: open_search_models.SearchRequestModel,
    ) -> open_search_models.SearchResponseModel:
        """
        系统提供了丰富的搜索语法以满足用户各种场景下的搜索需求。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return self.search_ex(app_name, request, runtime)

    async def search_async(
        self,
        app_name: str,
        request: open_search_models.SearchRequestModel,
    ) -> open_search_models.SearchResponseModel:
        """
        系统提供了丰富的搜索语法以满足用户各种场景下的搜索需求。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return await self.search_ex_async(app_name, request, runtime)

    def suggest_ex(
        self,
        app_name: str,
        model_name: str,
        request: open_search_models.SuggestRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.SuggestResponseModel:
        """
        下拉提示是搜索服务的基础功能,在用户输入查询词的过程中,智能推荐候选query,减少用户输入,帮助用户尽快找到想要的内容。
        """
        return TeaCore.from_map(
            open_search_models.SuggestResponseModel(),
            self._request(
                'GET',
                f'/v3/openapi/apps/{app_name}/suggest/{model_name}/search',
                TeaCore.to_map(request.query), request.headers, None, runtime))

    async def suggest_ex_async(
        self,
        app_name: str,
        model_name: str,
        request: open_search_models.SuggestRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.SuggestResponseModel:
        """
        下拉提示是搜索服务的基础功能,在用户输入查询词的过程中,智能推荐候选query,减少用户输入,帮助用户尽快找到想要的内容。
        """
        return TeaCore.from_map(
            open_search_models.SuggestResponseModel(), await
            self._request_async(
                'GET',
                f'/v3/openapi/apps/{app_name}/suggest/{model_name}/search',
                TeaCore.to_map(request.query), request.headers, None, runtime))

    def suggest(
        self,
        app_name: str,
        model_name: str,
        request: open_search_models.SuggestRequestModel,
    ) -> open_search_models.SuggestResponseModel:
        """
        下拉提示是搜索服务的基础功能,在用户输入查询词的过程中,智能推荐候选query,减少用户输入,帮助用户尽快找到想要的内容。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return self.suggest_ex(app_name, model_name, request, runtime)

    async def suggest_async(
        self,
        app_name: str,
        model_name: str,
        request: open_search_models.SuggestRequestModel,
    ) -> open_search_models.SuggestResponseModel:
        """
        下拉提示是搜索服务的基础功能,在用户输入查询词的过程中,智能推荐候选query,减少用户输入,帮助用户尽快找到想要的内容。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return await self.suggest_ex_async(app_name, model_name, request,
                                           runtime)

    def push_document_ex(
        self,
        app_name: str,
        table_name: str,
        request: open_search_models.PushDocumentRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.PushDocumentResponseModel:
        """
        支持新增、更新、删除 等操作,以及对应批量操作
        """
        return TeaCore.from_map(
            open_search_models.PushDocumentResponseModel(),
            self._request(
                'POST',
                f'/v3/openapi/apps/{app_name}/{table_name}/actions/bulk', None,
                request.headers, request.body, runtime))

    async def push_document_ex_async(
        self,
        app_name: str,
        table_name: str,
        request: open_search_models.PushDocumentRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.PushDocumentResponseModel:
        """
        支持新增、更新、删除 等操作,以及对应批量操作
        """
        return TeaCore.from_map(
            open_search_models.PushDocumentResponseModel(), await
            self._request_async(
                'POST',
                f'/v3/openapi/apps/{app_name}/{table_name}/actions/bulk', None,
                request.headers, request.body, runtime))

    def push_document(
        self,
        app_name: str,
        table_name: str,
        request: open_search_models.PushDocumentRequestModel,
    ) -> open_search_models.PushDocumentResponseModel:
        """
        支持新增、更新、删除 等操作,以及对应批量操作
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return self.push_document_ex(app_name, table_name, request, runtime)

    async def push_document_async(
        self,
        app_name: str,
        table_name: str,
        request: open_search_models.PushDocumentRequestModel,
    ) -> open_search_models.PushDocumentResponseModel:
        """
        支持新增、更新、删除 等操作,以及对应批量操作
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return await self.push_document_ex_async(app_name, table_name, request,
                                                 runtime)

    def collect_data_ex(
        self,
        app_name: str,
        collector_name: str,
        request: open_search_models.CollectDataRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.CollectDataResponseModel:
        """
        为了给客户提供更高质量的搜索效果,opensearch目前支持客户通过server端上传点击数据。
        """
        return TeaCore.from_map(
            open_search_models.CollectDataResponseModel(),
            self._request(
                'POST',
                f'/v3/openapi/app-groups/{app_name}/data-collections/{collector_name}/actions/bulk',
                None, request.headers, request.body, runtime))

    async def collect_data_ex_async(
        self,
        app_name: str,
        collector_name: str,
        request: open_search_models.CollectDataRequestModel,
        runtime: util_models.RuntimeOptions,
    ) -> open_search_models.CollectDataResponseModel:
        """
        为了给客户提供更高质量的搜索效果,opensearch目前支持客户通过server端上传点击数据。
        """
        return TeaCore.from_map(
            open_search_models.CollectDataResponseModel(), await
            self._request_async(
                'POST',
                f'/v3/openapi/app-groups/{app_name}/data-collections/{collector_name}/actions/bulk',
                None, request.headers, request.body, runtime))

    def collect_data(
        self,
        app_name: str,
        collector_name: str,
        request: open_search_models.CollectDataRequestModel,
    ) -> open_search_models.CollectDataResponseModel:
        """
        为了给客户提供更高质量的搜索效果,opensearch目前支持客户通过server端上传点击数据。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return self.collect_data_ex(app_name, collector_name, request, runtime)

    async def collect_data_async(
        self,
        app_name: str,
        collector_name: str,
        request: open_search_models.CollectDataRequestModel,
    ) -> open_search_models.CollectDataResponseModel:
        """
        为了给客户提供更高质量的搜索效果,opensearch目前支持客户通过server端上传点击数据。
        """
        runtime = util_models.RuntimeOptions(connect_timeout=5000,
                                             read_timeout=10000,
                                             autoretry=False,
                                             ignore_ssl=False,
                                             max_idle_conns=50)
        return await self.collect_data_ex_async(app_name, collector_name,
                                                request, runtime)

    def set_user_agent(
        self,
        user_agent: str,
    ) -> None:
        self._user_agent = user_agent

    def append_user_agent(
        self,
        user_agent: str,
    ) -> None:
        self._user_agent = f'{self._user_agent} {user_agent}'

    def get_user_agent(self) -> str:
        user_agent = UtilClient.get_user_agent(self._user_agent)
        return user_agent

    def get_access_key_id(self) -> str:
        if UtilClient.is_unset(self._credential):
            return ''
        access_key_id = self._credential.get_access_key_id()
        return access_key_id

    async def get_access_key_id_async(self) -> str:
        if UtilClient.is_unset(self._credential):
            return ''
        access_key_id = await self._credential.get_access_key_id_async()
        return access_key_id

    def get_access_key_secret(self) -> str:
        if UtilClient.is_unset(self._credential):
            return ''
        secret = self._credential.get_access_key_secret()
        return secret

    async def get_access_key_secret_async(self) -> str:
        if UtilClient.is_unset(self._credential):
            return ''
        secret = await self._credential.get_access_key_secret_async()
        return secret
Ejemplo n.º 6
0
class Client:
    """
    This is for ROA SDK
    """
    _protocol: str = None
    _read_timeout: int = None
    _connect_timeout: int = None
    _http_proxy: str = None
    _https_proxy: str = None
    _no_proxy: str = None
    _max_idle_conns: int = None
    _endpoint_host: str = None
    _network: str = None
    _endpoint_rule: str = None
    _endpoint_map: Dict[str, str] = None
    _suffix: str = None
    _product_id: str = None
    _region_id: str = None
    _user_agent: str = None
    _credential: CredentialClient = None

    def __init__(
        self,
        config: roa_models.Config,
    ):
        """
        Init client with Config
        @param config: config contains the necessary information to create a client
        """
        if UtilClient.is_unset(config):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config' can not be unset"
            })
        UtilClient.validate_model(config)
        if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(
                config.access_key_secret):
            if not UtilClient.empty(config.security_token):
                config.type = 'sts'
            else:
                config.type = 'access_key'
            credential_config = credential_models.Config(
                access_key_id=config.access_key_id,
                type=config.type,
                access_key_secret=config.access_key_secret,
                security_token=config.security_token)
            self._credential = CredentialClient(credential_config)
        elif not UtilClient.is_unset(config.credential):
            self._credential = config.credential
        else:
            raise TeaException({
                'code':
                'ParameterMissing',
                'message':
                "'accessKeyId' and 'accessKeySecret' or 'credential' can not be unset"
            })
        self._region_id = config.region_id
        self._protocol = config.protocol
        self._endpoint_host = config.endpoint
        self._read_timeout = config.read_timeout
        self._connect_timeout = config.connect_timeout
        self._http_proxy = config.http_proxy
        self._https_proxy = config.https_proxy
        self._max_idle_conns = config.max_idle_conns

    def do_request(
        self,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'content-type'] = 'application/json; charset=utf-8'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self._credential.get_access_key_id()
                    access_key_secret = self._credential.get_access_key_secret(
                    )
                    security_token = self._credential.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = UtilClient.read_as_json(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    async def do_request_async(
        self,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'content-type'] = 'application/json; charset=utf-8'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = await self._credential.get_access_key_id_async(
                    )
                    access_key_secret = await self._credential.get_access_key_secret_async(
                    )
                    security_token = await self._credential.get_security_token_async(
                    )
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = await TeaCore.async_do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = await UtilClient.read_as_json_async(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_request_with_action(
        self,
        action: str,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param action: api name
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'x-acs-action': action,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'content-type'] = 'application/json; charset=utf-8'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self._credential.get_access_key_id()
                    access_key_secret = self._credential.get_access_key_secret(
                    )
                    security_token = self._credential.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = UtilClient.read_as_json(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    async def do_request_with_action_async(
        self,
        action: str,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Any,
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param action: api name
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'x-acs-action': action,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = UtilClient.to_jsonstring(body)
                    _request.headers[
                        'content-type'] = 'application/json; charset=utf-8'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = await self._credential.get_access_key_id_async(
                    )
                    access_key_secret = await self._credential.get_access_key_secret_async(
                    )
                    security_token = await self._credential.get_security_token_async(
                    )
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = await TeaCore.async_do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = await UtilClient.read_as_json_async(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_request_with_form(
        self,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Dict[str, Any],
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = ROAUtilClient.to_form(body)
                    _request.headers[
                        'content-type'] = 'application/x-www-form-urlencoded'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self._credential.get_access_key_id()
                    access_key_secret = self._credential.get_access_key_secret(
                    )
                    security_token = self._credential.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = UtilClient.read_as_json(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    async def do_request_with_form_async(
        self,
        version: str,
        protocol: str,
        method: str,
        auth_type: str,
        pathname: str,
        query: Dict[str, str],
        headers: Dict[str, str],
        body: Dict[str, Any],
        runtime: util_models.RuntimeOptions,
    ) -> dict:
        """
        Encapsulate the request and invoke the network
        @param version: product version
        @param protocol: http or https
        @param method: e.g. GET
        @param auth_type: when authType is Anonymous, the signature will not be calculate
        @param pathname: pathname of every api
        @param query: which contains request params
        @param headers: request headers
        @param body: content of request
        @param runtime: which controls some details of call api, such as retry times
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted':
            'retry',
            'readTimeout':
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            'connectTimeout':
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            'httpProxy':
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy':
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy':
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns':
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts':
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy,
                                                    'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL':
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        'date': UtilClient.get_date_utcstring(),
                        'host': self._endpoint_host,
                        'accept': 'application/json',
                        'x-acs-signature-nonce': UtilClient.get_nonce(),
                        'x-acs-signature-method': 'HMAC-SHA1',
                        'x-acs-signature-version': '1.0',
                        'x-acs-version': version,
                        'user-agent': UtilClient.get_user_agent(
                            self._user_agent),
                        # x-sdk-client': helper.DEFAULT_CLIENT
                    },
                    headers)
                if not UtilClient.is_unset(body):
                    _request.body = ROAUtilClient.to_form(body)
                    _request.headers[
                        'content-type'] = 'application/x-www-form-urlencoded'
                if not UtilClient.is_unset(query):
                    _request.query = query
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = await self._credential.get_access_key_id_async(
                    )
                    access_key_secret = await self._credential.get_access_key_secret_async(
                    )
                    security_token = await self._credential.get_security_token_async(
                    )
                    if not UtilClient.empty(security_token):
                        _request.headers['x-acs-accesskey-id'] = access_key_id
                        _request.headers[
                            'x-acs-security-token'] = security_token
                    string_to_sign = ROAUtilClient.get_string_to_sign(_request)
                    _request.headers['authorization'] = 'acs %s:%s' % (
                        access_key_id,
                        ROAUtilClient.get_signature(string_to_sign,
                                                    access_key_secret))
                _last_request = _request
                _response = await TeaCore.async_do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {'headers': _response.headers}
                result = await UtilClient.read_as_json_async(_response.body)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    err = UtilClient.assert_as_map(result)
                    raise TeaException({
                        'code':
                        '%s' %
                        self.default_any(err.get('Code'), err.get('code')),
                        'message':
                        'code: %s, %s request id: %s' %
                        (_response.status_code,
                         self.default_any(err.get('Message'),
                                          err.get('message')),
                         self.default_any(err.get('RequestId'),
                                          err.get('requestId'))),
                        'data':
                        err
                    })
                return {'headers': _response.headers, 'body': result}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    @staticmethod
    def default_any(
        input_value: Any,
        default_value: Any,
    ) -> Any:
        """
        If inputValue is not null, return it or return defaultValue
        @param input_value:  users input value
        @param default_value: default value
        @return: the final result
        """
        if UtilClient.is_unset(input_value):
            return default_value
        return input_value

    def check_config(
        self,
        config: roa_models.Config,
    ) -> None:
        """
        If the endpointRule and config.endpoint are empty, throw error
        @param config: config contains the necessary information to create a client
        """
        if UtilClient.empty(self._endpoint_rule) and UtilClient.empty(
                config.endpoint):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config.endpoint' can not be empty"
            })
Ejemplo n.º 7
0
    def __init__(self,
                 config,
                 _endpoint=None,
                 _region_id=None,
                 _protocol=None,
                 _user_agent=None,
                 _endpoint_rule=None,
                 _endpoint_map=None,
                 _suffix=None,
                 _read_timeout=None,
                 _connect_timeout=None,
                 _http_proxy=None,
                 _https_proxy=None,
                 _socks_5proxy=None,
                 _socks_5net_work=None,
                 _no_proxy=None,
                 _network=None,
                 _product_id=None,
                 _max_idle_conns=None,
                 _endpoint_type=None,
                 _open_platform_endpoint=None,
                 _credential=None):
        """
        Init client with Config

        :param config: config contains the necessary information to create a client
        """
        self._endpoint = _endpoint
        self._region_id = _region_id
        self._protocol = _protocol
        self._user_agent = _user_agent
        self._endpoint_rule = _endpoint_rule
        self._endpoint_map = _endpoint_map
        self._suffix = _suffix
        self._read_timeout = _read_timeout
        self._connect_timeout = _connect_timeout
        self._http_proxy = _http_proxy
        self._https_proxy = _https_proxy
        self._socks_5proxy = _socks_5proxy
        self._socks_5net_work = _socks_5net_work
        self._no_proxy = _no_proxy
        self._network = _network
        self._product_id = _product_id
        self._max_idle_conns = _max_idle_conns
        self._endpoint_type = _endpoint_type
        self._open_platform_endpoint = _open_platform_endpoint
        self._credential = _credential
        if UtilClient.is_unset(config):
            raise TeaException({
                "code": "ParameterMissing",
                "message": "'config' can not be unset"
            })
        if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(
                config.access_key_secret):
            if not UtilClient.empty(config.security_token):
                config.type = "sts"
            else:
                config.type = "access_key"
            credential_config = credential_models.Config(
                access_key_id=config.access_key_id,
                type=config.type,
                access_key_secret=config.access_key_secret,
                security_token=config.security_token)
            self._credential = CredentialClient(credential_config)
        elif not UtilClient.is_unset(config.credential):
            self._credential = config.credential
        self._endpoint = config.endpoint
        self._protocol = config.protocol
        self._region_id = config.region_id
        self._user_agent = config.user_agent
        self._read_timeout = config.read_timeout
        self._connect_timeout = config.connect_timeout
        self._http_proxy = config.http_proxy
        self._https_proxy = config.https_proxy
        self._no_proxy = config.no_proxy
        self._socks_5proxy = config.socks_5proxy
        self._socks_5net_work = config.socks_5net_work
        self._max_idle_conns = config.max_idle_conns
Ejemplo n.º 8
0
class Client(object):
    """
    This is for OpenApi SDK
    """
    def __init__(self,
                 config,
                 _endpoint=None,
                 _region_id=None,
                 _protocol=None,
                 _user_agent=None,
                 _endpoint_rule=None,
                 _endpoint_map=None,
                 _suffix=None,
                 _read_timeout=None,
                 _connect_timeout=None,
                 _http_proxy=None,
                 _https_proxy=None,
                 _socks_5proxy=None,
                 _socks_5net_work=None,
                 _no_proxy=None,
                 _network=None,
                 _product_id=None,
                 _max_idle_conns=None,
                 _endpoint_type=None,
                 _open_platform_endpoint=None,
                 _credential=None):
        """
        Init client with Config

        :param config: config contains the necessary information to create a client
        """
        self._endpoint = _endpoint
        self._region_id = _region_id
        self._protocol = _protocol
        self._user_agent = _user_agent
        self._endpoint_rule = _endpoint_rule
        self._endpoint_map = _endpoint_map
        self._suffix = _suffix
        self._read_timeout = _read_timeout
        self._connect_timeout = _connect_timeout
        self._http_proxy = _http_proxy
        self._https_proxy = _https_proxy
        self._socks_5proxy = _socks_5proxy
        self._socks_5net_work = _socks_5net_work
        self._no_proxy = _no_proxy
        self._network = _network
        self._product_id = _product_id
        self._max_idle_conns = _max_idle_conns
        self._endpoint_type = _endpoint_type
        self._open_platform_endpoint = _open_platform_endpoint
        self._credential = _credential
        if UtilClient.is_unset(config):
            raise TeaException({
                "code": "ParameterMissing",
                "message": "'config' can not be unset"
            })
        if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(
                config.access_key_secret):
            if not UtilClient.empty(config.security_token):
                config.type = "sts"
            else:
                config.type = "access_key"
            credential_config = credential_models.Config(
                access_key_id=config.access_key_id,
                type=config.type,
                access_key_secret=config.access_key_secret,
                security_token=config.security_token)
            self._credential = CredentialClient(credential_config)
        elif not UtilClient.is_unset(config.credential):
            self._credential = config.credential
        self._endpoint = config.endpoint
        self._protocol = config.protocol
        self._region_id = config.region_id
        self._user_agent = config.user_agent
        self._read_timeout = config.read_timeout
        self._connect_timeout = config.connect_timeout
        self._http_proxy = config.http_proxy
        self._https_proxy = config.https_proxy
        self._no_proxy = config.no_proxy
        self._socks_5proxy = config.socks_5proxy
        self._socks_5net_work = config.socks_5net_work
        self._max_idle_conns = config.max_idle_conns

    def do_rpcrequest(self, action, version, protocol, method, auth_type,
                      body_type, request, runtime):
        """
        Encapsulate the request and invoke the network

        :type action: str
        :param action: api name

        :type version: str
        :param version: product version

        :type protocol: str
        :param protocol: http or https

        :type method: str
        :param method: e.g. GET

        :type auth_type: str
        :param auth_type: authorization type e.g. AK

        :type body_type: str
        :param body_type: response body type e.g. String

        :param request: object of OpenApiRequest

        :param runtime: which controls some details of call api, such as retry times

        :return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            "timeouted":
            "retry",
            "readTimeout":
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            "connectTimeout":
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            "httpProxy":
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            "httpsProxy":
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            "noProxy":
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            "maxIdleConns":
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            "retry": {
                "retryable": runtime.autoretry,
                "maxAttempts":
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            "backoff": {
                "policy": UtilClient.default_string(runtime.backoff_policy,
                                                    "no"),
                "period": UtilClient.default_number(runtime.backoff_period, 1)
            },
            "ignoreSSL":
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = "/"
                _request.query = TeaCore.merge(
                    {
                        "Action": action,
                        "Format": "json",
                        "Version": version,
                        "Timestamp": OpenApiUtilClient.get_timestamp(),
                        "SignatureNonce": UtilClient.get_nonce()
                    }, request.query)
                # endpoint is setted in product client
                _request.headers = {
                    "host": self._endpoint,
                    "x-acs-version": version,
                    "x-acs-action": action,
                    "user-agent": self.get_user_agent()
                }
                if not UtilClient.is_unset(request.body):
                    tmp = UtilClient.anyify_map_value(
                        OpenApiUtilClient.query(request.body))
                    _request.body = UtilClient.to_form_string(tmp)
                    _request.headers[
                        "content-type"] = "application/x-www-form-urlencoded"
                if not UtilClient.equal_string(auth_type, "Anonymous"):
                    access_key_id = self.get_access_key_id()
                    access_key_secret = self.get_access_key_secret()
                    security_token = self.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.query["SecurityToken"] = security_token
                    _request.query["SignatureMethod"] = "HMAC-SHA1"
                    _request.query["SignatureVersion"] = "1.0"
                    _request.query["AccessKeyId"] = access_key_id
                    signed_param = TeaCore.merge(
                        _request.query, OpenApiUtilClient.query(request.body))
                    _request.query[
                        "Signature"] = OpenApiUtilClient.get_rpcsignature(
                            signed_param, _request.method, access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    raise TeaException({
                        "message": err.get('Message'),
                        "data": err,
                        "code": err.get('Code')
                    })
                if UtilClient.equal_string(body_type, "binary"):
                    resp = {
                        "body": _response.body,
                        "headers": _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, "byte"):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {"body": byt, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "string"):
                    str = UtilClient.read_as_string(_response.body)
                    return {"body": str, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "json"):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {"body": res, "headers": _response.headers}
                else:
                    return {"headers": _response.headers}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_roarequest(self, action, version, protocol, method, auth_type,
                      pathname, body_type, request, runtime):
        """
        Encapsulate the request and invoke the network

        :type action: str
        :param action: api name

        :type version: str
        :param version: product version

        :type protocol: str
        :param protocol: http or https

        :type method: str
        :param method: e.g. GET

        :type auth_type: str
        :param auth_type: authorization type e.g. AK

        :type pathname: str
        :param pathname: pathname of every api

        :type body_type: str
        :param body_type: response body type e.g. String

        :param request: object of OpenApiRequest

        :param runtime: which controls some details of call api, such as retry times

        :return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            "timeouted":
            "retry",
            "readTimeout":
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            "connectTimeout":
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            "httpProxy":
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            "httpsProxy":
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            "noProxy":
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            "maxIdleConns":
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            "retry": {
                "retryable": runtime.autoretry,
                "maxAttempts":
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            "backoff": {
                "policy": UtilClient.default_string(runtime.backoff_policy,
                                                    "no"),
                "period": UtilClient.default_number(runtime.backoff_period, 1)
            },
            "ignoreSSL":
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        "date": UtilClient.get_date_utcstring(),
                        "host": self._endpoint,
                        "accept": "application/json",
                        "x-acs-signature-nonce": UtilClient.get_nonce(),
                        "x-acs-signature-method": "HMAC-SHA1",
                        "x-acs-signature-version": "1.0",
                        "x-acs-version": version,
                        "x-acs-action": action,
                        "user-agent": UtilClient.get_user_agent(
                            self._user_agent)
                    }, request.headers)
                if not UtilClient.is_unset(request.body):
                    _request.body = UtilClient.to_jsonstring(request.body)
                    _request.headers[
                        "content-type"] = "application/json; charset=UTF-8;"
                if not UtilClient.is_unset(request.query):
                    _request.query = request.query
                if not UtilClient.equal_string(auth_type, "Anonymous"):
                    access_key_id = self._credential.get_access_key_id()
                    access_key_secret = self._credential.get_access_key_secret(
                    )
                    security_token = self._credential.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers["x-acs-accesskey-id"] = access_key_id
                        _request.headers[
                            "x-acs-security-token"] = security_token
                    string_to_sign = OpenApiUtilClient.get_string_to_sign(
                        _request)
                    _request.headers["authorization"] = "acs " + str(
                        access_key_id) + ":" + str(
                            OpenApiUtilClient.get_roasignature(
                                string_to_sign, access_key_secret)) + ""
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {"headers": _response.headers}
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    raise TeaException({
                        "message": err.get('Message'),
                        "data": err,
                        "code": err.get('Code')
                    })
                if UtilClient.equal_string(body_type, "binary"):
                    resp = {
                        "body": _response.body,
                        "headers": _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, "byte"):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {"body": byt, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "string"):
                    str = UtilClient.read_as_string(_response.body)
                    return {"body": str, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "json"):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {"body": res, "headers": _response.headers}
                else:
                    return {"headers": _response.headers}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def do_roarequest_with_form(self, action, version, protocol, method,
                                auth_type, pathname, body_type, request,
                                runtime):
        """
        Encapsulate the request and invoke the network with form body

        :type action: str
        :param action: api name

        :type version: str
        :param version: product version

        :type protocol: str
        :param protocol: http or https

        :type method: str
        :param method: e.g. GET

        :type auth_type: str
        :param auth_type: authorization type e.g. AK

        :type pathname: str
        :param pathname: pathname of every api

        :type body_type: str
        :param body_type: response body type e.g. String

        :param request: object of OpenApiRequest

        :param runtime: which controls some details of call api, such as retry times

        :return: the response
        """
        request.validate()
        runtime.validate()
        _runtime = {
            "timeouted":
            "retry",
            "readTimeout":
            UtilClient.default_number(runtime.read_timeout,
                                      self._read_timeout),
            "connectTimeout":
            UtilClient.default_number(runtime.connect_timeout,
                                      self._connect_timeout),
            "httpProxy":
            UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            "httpsProxy":
            UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            "noProxy":
            UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            "maxIdleConns":
            UtilClient.default_number(runtime.max_idle_conns,
                                      self._max_idle_conns),
            "retry": {
                "retryable": runtime.autoretry,
                "maxAttempts":
                UtilClient.default_number(runtime.max_attempts, 3)
            },
            "backoff": {
                "policy": UtilClient.default_string(runtime.backoff_policy,
                                                    "no"),
                "period": UtilClient.default_number(runtime.backoff_period, 1)
            },
            "ignoreSSL":
            runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(
                    _runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(
                    self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.headers = TeaCore.merge(
                    {
                        "date": UtilClient.get_date_utcstring(),
                        "host": self._endpoint,
                        "accept": "application/json",
                        "x-acs-signature-nonce": UtilClient.get_nonce(),
                        "x-acs-signature-method": "HMAC-SHA1",
                        "x-acs-signature-version": "1.0",
                        "x-acs-version": version,
                        "x-acs-action": action,
                        "user-agent": UtilClient.get_user_agent(
                            self._user_agent)
                    }, request.headers)
                if not UtilClient.is_unset(request.body):
                    _request.body = OpenApiUtilClient.to_form(request.body)
                    _request.headers[
                        "content-type"] = "application/x-www-form-urlencoded"
                if not UtilClient.is_unset(request.query):
                    _request.query = request.query
                if not UtilClient.equal_string(auth_type, "Anonymous"):
                    access_key_id = self._credential.get_access_key_id()
                    access_key_secret = self._credential.get_access_key_secret(
                    )
                    security_token = self._credential.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.headers["x-acs-accesskey-id"] = access_key_id
                        _request.headers[
                            "x-acs-security-token"] = security_token
                    string_to_sign = OpenApiUtilClient.get_string_to_sign(
                        _request)
                    _request.headers["authorization"] = "acs " + str(
                        access_key_id) + ":" + str(
                            OpenApiUtilClient.get_roasignature(
                                string_to_sign, access_key_secret)) + ""
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                if UtilClient.equal_number(_response.status_code, 204):
                    return {"headers": _response.headers}
                if UtilClient.is_4xx(
                        _response.status_code) or UtilClient.is_5xx(
                            _response.status_code):
                    _res = UtilClient.read_as_json(_response.body)
                    err = UtilClient.assert_as_map(_res)
                    raise TeaException({
                        "message": err.get('Message'),
                        "data": err,
                        "code": err.get('Code')
                    })
                if UtilClient.equal_string(body_type, "binary"):
                    resp = {
                        "body": _response.body,
                        "headers": _response.headers
                    }
                    return resp
                elif UtilClient.equal_string(body_type, "byte"):
                    byt = UtilClient.read_as_bytes(_response.body)
                    return {"body": byt, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "string"):
                    str = UtilClient.read_as_string(_response.body)
                    return {"body": str, "headers": _response.headers}
                elif UtilClient.equal_string(body_type, "json"):
                    obj = UtilClient.read_as_json(_response.body)
                    res = UtilClient.assert_as_map(obj)
                    return {"body": res, "headers": _response.headers}
                else:
                    return {"headers": _response.headers}
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def get_user_agent(self):
        """
        Get user agent

        :return: user agent
        """
        user_agent = UtilClient.get_user_agent(self._user_agent)
        return user_agent

    def get_access_key_id(self):
        """
        Get accesskey id by using credential

        :return: accesskey id
        """
        if UtilClient.is_unset(self._credential):
            return ''
        access_key_id = self._credential.get_access_key_id()
        return access_key_id

    def get_access_key_secret(self):
        """
        Get accesskey secret by using credential

        :return: accesskey secret
        """
        if UtilClient.is_unset(self._credential):
            return ''
        secret = self._credential.get_access_key_secret()
        return secret

    def get_security_token(self):
        """
        Get security token by using credential

        :return: security token
        """
        if UtilClient.is_unset(self._credential):
            return ''
        token = self._credential.get_security_token()
        return token

    @staticmethod
    def default_any(input_value, default_value):
        """
        If inputValue is not null, return it or return defaultValue

        :type input_value: any
        :param input_value:  users input value

        :type default_value: any
        :param default_value: default value

        :return: the final result
        """
        if UtilClient.is_unset(input_value):
            return default_value
        return input_value

    def check_config(self, config):
        """
        If the endpointRule and config.endpoint are empty, throw error

        :param config: config contains the necessary information to create a client
        """
        if UtilClient.empty(self._endpoint_rule) and UtilClient.empty(
                config.endpoint):
            raise TeaException({
                "code": "ParameterMissing",
                "message": "'config.endpoint' can not be empty"
            })
Ejemplo n.º 9
0
class Client(object):
    """
    This is for RPC SDK
    """
    _endpoint = None  # type: unicode
    _region_id = None  # type: unicode
    _protocol = None  # type: unicode
    _user_agent = None  # type: unicode
    _endpoint_rule = None  # type: unicode
    _endpoint_map = None  # type: dict[unicode, unicode]
    _suffix = None  # type: unicode
    _read_timeout = None  # type: int
    _connect_timeout = None  # type: int
    _http_proxy = None  # type: unicode
    _https_proxy = None  # type: unicode
    _socks_5proxy = None  # type: unicode
    _socks_5net_work = None  # type: unicode
    _no_proxy = None  # type: unicode
    _network = None  # type: unicode
    _product_id = None  # type: unicode
    _max_idle_conns = None  # type: int
    _endpoint_type = None  # type: unicode
    _open_platform_endpoint = None  # type: unicode
    _credential = None  # type: CredentialClient

    def __init__(self, config):
        """
        Init client with Config

        @param config: config contains the necessary information to create a client
        """
        if UtilClient.is_unset(config):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config' can not be unset"
            })
        UtilClient.validate_model(config)
        if not UtilClient.empty(config.access_key_id) and not UtilClient.empty(config.access_key_secret):
            if not UtilClient.empty(config.security_token):
                config.type = 'sts'
            else:
                config.type = 'access_key'
            credential_config = credential_models.Config(
                access_key_id=config.access_key_id,
                type=config.type,
                access_key_secret=config.access_key_secret,
                security_token=config.security_token
            )
            self._credential = CredentialClient(credential_config)
        elif not UtilClient.is_unset(config.credential):
            self._credential = config.credential
        else:
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'accessKeyId' and 'accessKeySecret' or 'credential' can not be unset"
            })
        self._network = config.network
        self._suffix = config.suffix
        self._endpoint = config.endpoint
        self._protocol = config.protocol
        self._region_id = config.region_id
        self._user_agent = config.user_agent
        self._read_timeout = config.read_timeout
        self._connect_timeout = config.connect_timeout
        self._http_proxy = config.http_proxy
        self._https_proxy = config.https_proxy
        self._no_proxy = config.no_proxy
        self._socks_5proxy = config.socks_5proxy
        self._socks_5net_work = config.socks_5net_work
        self._max_idle_conns = config.max_idle_conns
        self._endpoint_type = config.endpoint_type
        self._open_platform_endpoint = config.open_platform_endpoint

    def do_request(self, action, protocol, method, version, auth_type, query, body, runtime):
        """
        Encapsulate the request and invoke the network

        @type action: unicode
        @param action: api name

        @type protocol: unicode
        @param protocol: http or https

        @type method: unicode
        @param method: e.g. GET

        @type version: unicode
        @param version: product version

        @type auth_type: unicode
        @param auth_type: when authType is Anonymous, the signature will not be calculate

        @param pathname: pathname of every api

        @type query: dict
        @param query: which contains request params

        @type body: dict
        @param body: content of request

        @param runtime: which controls some details of call api, such as retry times

        @rtype: dict
        @return: the response
        """
        runtime.validate()
        _runtime = {
            'timeouted': 'retry',
            'readTimeout': UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            'connectTimeout': UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            'httpProxy': UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            'httpsProxy': UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            'noProxy': UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            'maxIdleConns': UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            'retry': {
                'retryable': runtime.autoretry,
                'maxAttempts': UtilClient.default_number(runtime.max_attempts, 3)
            },
            'backoff': {
                'policy': UtilClient.default_string(runtime.backoff_policy, 'no'),
                'period': UtilClient.default_number(runtime.backoff_period, 1)
            },
            'ignoreSSL': runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, protocol)
                _request.method = method
                _request.pathname = '/'
                _request.query = RPCUtilClient.query(TeaCore.merge({
                    'Action': action,
                    'Format': 'json',
                    'Timestamp': RPCUtilClient.get_timestamp(),
                    'Version': version,
                    'SignatureNonce': UtilClient.get_nonce()
                }, query))
                # endpoint is setted in product client
                _request.headers = {
                    'x-acs-version': version,
                    'x-acs-action': action,
                    'host': self._endpoint,
                    'user-agent': self.get_user_agent()
                }
                if not UtilClient.is_unset(body):
                    tmp = UtilClient.anyify_map_value(RPCUtilClient.query(body))
                    _request.body = UtilClient.to_form_string(tmp)
                    _request.headers['content-type'] = 'application/x-www-form-urlencoded'
                if not UtilClient.equal_string(auth_type, 'Anonymous'):
                    access_key_id = self.get_access_key_id()
                    access_key_secret = self.get_access_key_secret()
                    security_token = self.get_security_token()
                    if not UtilClient.empty(security_token):
                        _request.query['SecurityToken'] = security_token
                    _request.query['SignatureMethod'] = 'HMAC-SHA1'
                    _request.query['SignatureVersion'] = '1.0'
                    _request.query['AccessKeyId'] = access_key_id
                    signed_param = TeaCore.merge(_request.query,
                        RPCUtilClient.query(body))
                    _request.query['Signature'] = RPCUtilClient.get_signature_v1(signed_param, _request.method, access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                obj = UtilClient.read_as_json(_response.body)
                res = UtilClient.assert_as_map(obj)
                if UtilClient.is_4xx(_response.status_code) or UtilClient.is_5xx(_response.status_code):
                    raise TeaException({
                        'code': '%s' % TeaConverter.to_unicode(self.default_any(res.get('Code'), res.get('code'))),
                        'message': 'code: %s, %s request id: %s' % (TeaConverter.to_unicode(_response.status_code), TeaConverter.to_unicode(self.default_any(res.get('Message'), res.get('message'))), TeaConverter.to_unicode(self.default_any(res.get('RequestId'), res.get('requestId')))),
                        'data': res
                    })
                return res
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)

    def get_user_agent(self):
        """
        Get user agent

        @rtype: unicode
        @return: user agent
        """
        user_agent = UtilClient.get_user_agent(self._user_agent)
        return user_agent

    def get_access_key_id(self):
        """
        Get accesskey id by using credential

        @rtype: unicode
        @return: accesskey id
        """
        if UtilClient.is_unset(self._credential):
            return ''
        access_key_id = self._credential.get_access_key_id()
        return access_key_id

    def get_access_key_secret(self):
        """
        Get accesskey secret by using credential

        @rtype: unicode
        @return: accesskey secret
        """
        if UtilClient.is_unset(self._credential):
            return ''
        secret = self._credential.get_access_key_secret()
        return secret

    def get_security_token(self):
        """
        Get security token by using credential

        @rtype: unicode
        @return: security token
        """
        if UtilClient.is_unset(self._credential):
            return ''
        token = self._credential.get_security_token()
        return token

    def check_config(self, config):
        """
        If the endpointRule and config.endpoint are empty, throw error

        @param config: config contains the necessary information to create a client
        """
        if UtilClient.empty(self._endpoint_rule) and UtilClient.empty(config.endpoint):
            raise TeaException({
                'code': 'ParameterMissing',
                'message': "'config.endpoint' can not be empty"
            })

    @staticmethod
    def default_any(input_value, default_value):
        """
        If inputValue is not null, return it or return defaultValue

        @param input_value:  users input value

        @param default_value: default value

        @return: the final result
        """
        if UtilClient.is_unset(input_value):
            return default_value
        return input_value