Example #1
0
 def test_from_map(self):
     option = RuntimeOptions()
     dic = {
         'autoretry': True,
         'ignoreSSL': True,
         'max_attempts': 1,
         'backoff_policy': 'test',
         'backoff_period': 1,
         'readTimeout': 1,
         'connectTimeout': 1,
         'httpProxy': 'test',
         'httpsProxy': 'test',
         'noProxy': 'test',
         'maxIdleConns': 1,
         'localAddr': 'test',
         'socks5Proxy': 'test',
         'socks5NetWork': 'test'
     }
     option.from_map(dic)
     self.assertEqual(True, option.autoretry)
     self.assertEqual(True, option.ignore_ssl)
     self.assertEqual(1, option.max_attempts)
     self.assertEqual('test', option.backoff_policy)
     self.assertEqual(1, option.backoff_period)
     self.assertEqual(1, option.read_timeout)
     self.assertEqual(1, option.connect_timeout)
     self.assertEqual('test', option.http_proxy)
     self.assertEqual('test', option.https_proxy)
     self.assertEqual('test', option.no_proxy)
     self.assertEqual(1, option.max_idle_conns)
     self.assertEqual('test', option.local_addr)
     self.assertEqual('test', option.socks_5proxy)
     self.assertEqual('test', option.socks_5net_work)
Example #2
0
 def test_to_map(self):
     option = RuntimeOptions(
         autoretry=True,
         ignore_ssl=True,
         max_attempts=1,
         backoff_policy="test",
         backoff_period=1,
         read_timeout=1,
         connect_timeout=1,
         http_proxy="test",
         https_proxy="test",
         no_proxy="test",
         max_idle_conns=1,
         local_addr="test",
         socks_5proxy="test",
         socks_5net_work="test"
     )
     result = option.to_map()
     self.assertEqual(True, result.get('autoretry'))
     self.assertEqual(True, result.get('ignoreSSL'))
     self.assertEqual(1, result.get('max_attempts'))
     self.assertEqual('test', result.get('backoff_policy'))
     self.assertEqual(1, result.get('backoff_period'))
     self.assertEqual(1, result.get('readTimeout'))
     self.assertEqual(1, result.get('connectTimeout'))
     self.assertEqual('test', result.get('httpProxy'))
     self.assertEqual('test', result.get('httpsProxy'))
     self.assertEqual('test', result.get('noProxy'))
     self.assertEqual(1, result.get('maxIdleConns'))
     self.assertEqual('test', result.get('localAddr'))
     self.assertEqual('test', result.get('socks5Proxy'))
     self.assertEqual('test', result.get('socks5NetWork'))
Example #3
0
 def test_do_request(self):
     conf = Config(access_key_id='access_key_id',
                   access_key_secret='access_key_secret',
                   security_token='security_token',
                   protocol='http',
                   region_id='region_id',
                   read_timeout=10000,
                   connect_timeout=5000,
                   endpoint='127.0.0.1:8888',
                   max_idle_conns=1)
     runtime = RuntimeOptions(autoretry=False, max_attempts=2)
     client = Client(conf)
     res = client.do_request(protocol='http',
                             method='GET',
                             version='version',
                             auth_type='auth_type',
                             pathname='',
                             query={},
                             body=None,
                             headers={},
                             runtime=runtime)
     res.pop('headers')
     self.assertEqual({'body': {'result': 'server test'}}, res)
     try:
         client.do_request(protocol='http',
                           method='POST',
                           version='version',
                           auth_type='auth_type',
                           pathname='',
                           query={},
                           body=None,
                           headers={},
                           runtime=runtime)
     except Exception as e:
         self.assertIsInstance(e, UnretryableException)
Example #4
0
    def test_init(self):
        option = RuntimeOptions()
        option.validate()
        self.assertEqual(None, option.autoretry)

        option = RuntimeOptions(
            autoretry=True,
            ignore_ssl=True,
            max_attempts=1,
            backoff_policy="test",
            backoff_period=1,
            read_timeout=1,
            connect_timeout=1,
            http_proxy="test",
            https_proxy="test",
            no_proxy="test",
            max_idle_conns=1,
            local_addr="test",
            socks_5proxy="test",
            socks_5net_work="test"
        )
        self.assertEqual(True, option.autoretry)
        self.assertEqual(True, option.ignore_ssl)
        self.assertEqual(1, option.max_attempts)
        self.assertEqual('test', option.backoff_policy)
        self.assertEqual(1, option.backoff_period)
        self.assertEqual(1, option.read_timeout)
        self.assertEqual(1, option.connect_timeout)
        self.assertEqual('test', option.http_proxy)
        self.assertEqual('test', option.https_proxy)
        self.assertEqual('test', option.no_proxy)
        self.assertEqual(1, option.max_idle_conns)
        self.assertEqual('test', option.local_addr)
        self.assertEqual('test', option.socks_5proxy)
        self.assertEqual('test', option.socks_5net_work)
Example #5
0
 def test_client(self):
     config = Config(app_key=os.environ['IOT_APP_KEY'],
                     app_secret=os.environ['IOT_APP_SECRET'],
                     domain='api.link.aliyun.com')
     client = Client(config)
     request = CommonParams(api_ver='1.0.0')
     body = IoTApiRequest(params={'input': 'test'}, request=request)
     res = client.do_request('/kit/debug/ping', 'https', 'POST', None, body,
                             RuntimeOptions())
     print(res.body.decode('utf-8'))
     data = json.loads(res.body.decode('utf-8'))
     self.assertEqual(200, data['code'])
     self.assertEqual('test', data['data'])
Example #6
0
 async def request(method):
     conf = Config(access_key_id='access_key_id',
                   security_token='security_token',
                   protocol='http',
                   region_id='region_id',
                   read_timeout=1000,
                   connect_timeout=5000,
                   endpoint='127.0.0.1:8888',
                   max_idle_conns=1)
     conf.access_key_secret = 'access_key_secret'
     runtime = RuntimeOptions(autoretry=False, max_attempts=2)
     client = Client(conf)
     return await client.do_request_async(action='action',
                                          protocol='http',
                                          method=method,
                                          version='version',
                                          auth_type='auth_type',
                                          query={},
                                          body={},
                                          runtime=runtime)
Example #7
0
 def do_request(
     self,
     version: str,
     action: str,
     protocol: str,
     method: str,
     pathname: str,
     request: dict,
     headers: Dict[str, str],
     runtime: util_models.RuntimeOptions,
 ) -> dict:
     """
     Encapsulate the request and invoke the network
     @param action: api name
     @param protocol: http or https
     @param method: e.g. GET
     @param pathname: pathname of every api
     @param request: which contains request params
     @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),
         'maxIdleTimeMillis':
         self._max_idle_time_millis,
         'keepAliveDurationMillis':
         self._keep_alive_duration_millis,
         'maxRequests':
         self._max_requests,
         'maxRequestsPerHost':
         self._max_requests_per_host,
         '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.query = {
                 'method': action,
                 'version': version,
                 'sign_type': 'HmacSHA1',
                 'req_time': AntchainUtils.get_timestamp(),
                 'req_msg_id': AntchainUtils.get_nonce(),
                 'access_key': self._access_key_id,
                 'base_sdk_version': 'TeaSDK-2.0',
                 'sdk_version': '1.1.8'
             }
             if not UtilClient.empty(self._security_token):
                 _request.query['security_token'] = self._security_token
             _request.headers = TeaCore.merge(
                 {
                     'host':
                     UtilClient.default_string(
                         self._endpoint, 'openapi.antchain.antgroup.com'),
                     'user-agent':
                     UtilClient.get_user_agent(self._user_agent)
                 }, headers)
             tmp = UtilClient.anyify_map_value(RPCUtilClient.query(request))
             _request.body = UtilClient.to_form_string(tmp)
             _request.headers[
                 'content-type'] = 'application/x-www-form-urlencoded'
             signed_param = TeaCore.merge(_request.query,
                                          RPCUtilClient.query(request))
             _request.query['sign'] = AntchainUtils.get_signature(
                 signed_param, self._access_key_secret)
             _last_request = _request
             _response = TeaCore.do_action(_request, _runtime)
             raw = UtilClient.read_as_string(_response.body)
             obj = UtilClient.parse_json(raw)
             res = UtilClient.assert_as_map(obj)
             resp = UtilClient.assert_as_map(res.get('response'))
             if AntchainUtils.has_error(raw, self._access_key_secret):
                 raise TeaException({
                     'message': resp.get('result_msg'),
                     'data': resp,
                     'code': resp.get('result_code')
                 })
             return resp
         except Exception as e:
             if TeaCore.is_retryable(e):
                 _last_exception = e
                 continue
             raise e
     raise UnretryableException(_last_request, _last_exception)
 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)
Example #9
0
 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)
Example #10
0
 def do_request(
     self,
     action: str,
     protocol: str,
     method: str,
     version: str,
     auth_type: str,
     query: dict,
     body: dict,
     runtime: util_models.RuntimeOptions,
 ) -> dict:
     """
     Encapsulate the request and invoke the network
     @param action: api name
     @param protocol: http or https
     @param method: e.g. GET
     @param version: product version
     @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 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 = '/'
             _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' %
                     self.default_any(res.get('Code'), res.get('code')),
                     'message':
                     'code: %s, %s request id: %s' %
                     (_response.status_code,
                      self.default_any(res.get('Message'),
                                       res.get('message')),
                      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)