Exemplo n.º 1
0
 async def upload_merchant_image_ex_async(
     self,
     request: industry_models.UploadMerchantImageRequest,
     headers: Dict[str, str],
     runtime: util_models.RuntimeOptions,
 ) -> industry_models.UploadMerchantImageResponse:
     """
     Description: 行业商家图片上传
     Summary: 行业商家图片上传
     """
     if not UtilClient.is_unset(request.file_object):
         upload_req = industry_models.CreateAntcloudGatewayxFileUploadRequest(
             auth_token=request.auth_token,
             api_code='antcloud.industry.merchant.image.upload',
             file_name=request.file_object_name
         )
         upload_resp = await self.create_antcloud_gatewayx_file_upload_ex_async(upload_req, headers, runtime)
         if not AntchainUtils.is_success(upload_resp.result_code, 'ok'):
             upload_merchant_image_response = industry_models.UploadMerchantImageResponse(
                 req_msg_id=upload_resp.req_msg_id,
                 result_code=upload_resp.result_code,
                 result_msg=upload_resp.result_msg
             )
             return upload_merchant_image_response
         upload_headers = AntchainUtils.parse_upload_headers(upload_resp.upload_headers)
         await AntchainUtils.put_object_async(request.file_object, upload_headers, upload_resp.upload_url)
         request.file_id = upload_resp.file_id
     UtilClient.validate_model(request)
     return industry_models.UploadMerchantImageResponse().from_map(
         await self.do_request_async('1.0', 'antcloud.industry.merchant.image.upload', 'HTTPS', 'POST', f'/gateway.do', TeaCore.to_map(request), headers, runtime)
     )
Exemplo n.º 2
0
 async def echo_gateway_check_ex_async(
     self,
     request: demo_models.EchoGatewayCheckRequest,
     headers: Dict[str, str],
     runtime: util_models.RuntimeOptions,
 ) -> demo_models.EchoGatewayCheckResponse:
     """
     Description: Demo接口,返回当输入的值
     Summary: 返回输入值
     """
     if not UtilClient.is_unset(request.file_object):
         upload_req = demo_models.CreateAntcloudGatewayxFileUploadRequest(
             api_code='demo.gateway.check.echo')
         upload_resp = await self.create_antcloud_gatewayx_file_upload_ex_async(
             upload_req, headers, runtime)
         if not AntchainUtils.is_success(upload_resp.result_code, 'OK'):
             echo_gateway_check_response = demo_models.EchoGatewayCheckResponse(
                 req_msg_id=upload_resp.req_msg_id,
                 result_code=upload_resp.result_code,
                 result_msg=upload_resp.result_msg)
             return echo_gateway_check_response
         upload_headers = AntchainUtils.parse_upload_headers(
             upload_resp.upload_headers)
         await AntchainUtils.put_object_async(request.file_object,
                                              upload_headers,
                                              upload_resp.upload_url)
         request.file_id = upload_resp.file_id
     UtilClient.validate_model(request)
     return demo_models.EchoGatewayCheckResponse().from_map(
         await self.do_request_async('1.0', 'demo.gateway.check.echo',
                                     'HTTPS', 'POST', f'/gateway.do',
                                     TeaCore.to_map(request), headers,
                                     runtime))
    def test_is_success(self):
        s1 = 'OK'
        s2 = 'fail'
        self.assertTrue(AntchainUtils.is_success(s1, s2))

        s1 = 'fail'
        s2 = 'OK'
        self.assertFalse(AntchainUtils.is_success(s1, s2))

        s1 = 'fail'
        s2 = 'fail'
        self.assertTrue(AntchainUtils.is_success(s1, s2))
    def test_put_object(self):
        url = 'http://127.0.0.1:8888'
        with open('test.txt', 'rb') as f:
            AntchainUtils.put_object(f, {'expected': 'success'}, url)

        with open('test.txt', 'rb') as f:
            try:
                AntchainUtils.put_object(f, {'expected': 'fail'}, url)
                assert False
            except TeaException as e:
                self.assertEqual('NoSuchKey', e.code)
                self.assertEqual(400, e.data['httpCode'])
    def test_has_error(self):
        tmp = 'testInvalidJson'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertTrue(resp)

        tmp = '{"noResponse":"true"}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertTrue(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"false"},"sign":"IUl/4uLq7utFnsjF1Zy6B6OWbCg="}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertFalse(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"}}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertTrue(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"},"sign":"IUl/4uLq7utFnsjF1Zy6B6OWbCg="}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertFalse(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"},"sign":"IUl/4uLqtFnsjF1Zy6B6OWbCg="}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertTrue(resp)

        tmp = '{"response":{"signatureValue":"test","expired_time":"2021-01-04T17:04:42.072+08:00",' \
              '"file_id":"kjiac1a298f8d","req_msg_id":"79e093b3ae0f3f2c1","result_code":"OK"},' \
              '"sign":"IUl/4uLqtFnsjF1Zy6B6OWbCg="}'
        resp = AntchainUtils.has_error(tmp, 'secret')
        self.assertTrue(resp)
    def test_parse_upload_headers(self):
        res = AntchainUtils.parse_upload_headers(12)
        self.assertEqual({}, res)

        res = AntchainUtils.parse_upload_headers('{"test":"ok"}')
        self.assertEqual({}, res)

        res = AntchainUtils.parse_upload_headers([
            {
                "name": "content-type",
                "value": "text",
            },
            {
                "name": "content-md5",
                "value": "md5value",
            },
        ])
        self.assertEqual('text', res['content-type'])
        self.assertEqual('md5value', res['content-md5'])
Exemplo n.º 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 test_get_nonce(self):
     self.assertEqual(32, len(AntchainUtils.get_nonce()))
 def test_get_signature(self):
     params = {
         'test': 'ok'
     }
     signature = AntchainUtils.get_signature(params, 'secret')
     self.assertEqual('qlB4B1lFcehlWRelL7Fo4uNHPCs=', signature)
Exemplo n.º 10
0
 def test_get_timestamp(self):
     timestamp = AntchainUtils.get_timestamp()
     self.assertEqual(20, len(timestamp))