def _request(self, action, method, path, request):
     """公共请求方法
     :param action: Request action name.
     :param path: Request path.
     :param request: Request instance.
     :rtype: :class:`jrtzcloudsdkconsensus.v20191119.models.DescribeConsensusResponse`
     """
     try:
         params = request._serialize()
         body = self.call(action, method, path, params)
         response = json.loads(body)
         if response.get("Message"):
             raise JrtzCloudSDKException(response.get("Code"),
                                         response.get("Message"),
                                         response.get("RequestId"))
             raise JrtzCloudSDKException(code, message, reqid)
         else:
             model = models.DescribeConsensusResponse()
             model._deserialize(response)
             return model
     except Exception as e:
         if isinstance(e, JrtzCloudSDKException):
             raise
         else:
             raise JrtzCloudSDKException("JrtzCloudSDKClientError",
                                         e.message)
 def _project_request(self, action, method, path, request=None):
     """公共请求方法
     :param action: Request action name.
     :param path: Request path.
     :param request: Request instance.
     :rtype: :class:`jrtzcloudsdkblten.v20191119.models.ProjectResponse`
     """
     try:
         if request != None and hasattr(request, "ProjectId"):
             delattr(request, "ProjectId")
         params = None if request is None else request._serialize()
         body = self.call(action, method, path, params)
         response = json.loads(body)
         if response.get("Message"):
             raise JrtzCloudSDKException(response.get("Code"),
                                         response.get("Message"),
                                         response.get("RequestId"))
             raise JrtzCloudSDKException(code, message, reqid)
         else:
             model = models.ProjectResponse()
             model._deserialize(response)
             return model
     except Exception as e:
         if isinstance(e, JrtzCloudSDKException):
             raise
         else:
             raise JrtzCloudSDKException("JrtzCloudSDKClientError",
                                         e.message)
Ejemplo n.º 3
0
    def __init__(self, secretId, secretKey, token=None):
        """Investoday Cloud Credentials.

        Access https://console.cloud.Investoday.com/cam/capi to manage your
        credentials.

        :param secretId: The secret id of your credential.
        :type secretId: str
        :param secretKey: The secret key of your credential.
        :type secretKey: str
        :param token: The federation token of your credential, if this field
                      is specified, secretId and secretKey should be set
                      accordingly, see: https://cloud.Investoday.com/document/product/598/13896
        """
        if secretId is None or secretId.strip() == "":
            raise JrtzCloudSDKException(
                "InvalidCredential", "secret id should not be none or empty")
        if secretId.strip() != secretId:
            raise JrtzCloudSDKException("InvalidCredential",
                                        "secret id should not contain spaces")
        self.secretId = secretId

        if secretKey is None or secretKey.strip() == "":
            raise JrtzCloudSDKException(
                "InvalidCredential", "secret key should not be none or empty")
        if secretKey.strip() != secretKey:
            raise JrtzCloudSDKException(
                "InvalidCredential", "secret key should not contain spaces")
        self.secretKey = secretKey

        self.token = token
Ejemplo n.º 4
0
    def _format_params(self, prefix, params):
        d = {}
        if params is None:
            return d

        if not isinstance(params, (tuple, list, dict)):
            d[prefix] = params
            return d

        if isinstance(params, (list, tuple)):
            for idx, item in enumerate(params):
                if prefix:
                    key = "{0}.{1}".format(prefix, idx)
                else:
                    key = "{0}".format(idx)
                d.update(self._format_params(key, item))
            return d

        if isinstance(params, dict):
            for k, v in params.items():
                if prefix:
                    key = '{0}.{1}'.format(prefix, k)
                else:
                    key = '{0}'.format(k)
                d.update(self._format_params(key, v))
            return d

        raise JrtzCloudSDKException("ClientParamsError",
                                    "some params type error")
 def send_request(self, req_inter):
     try:
         self._request(req_inter)
         try:
             http_resp = self.conn.getresponse()
         except BadStatusLine:
             # open another connection when keep-alive timeout
             # httplib will not handle keep-alive timeout,
             # so we must handle it ourself
             if self.debug:
                 print("keep-alive timeout, reopen connection")
             self.conn.close()
             self._request(req_inter)
             http_resp = self.conn.getresponse()
         headers = dict(http_resp.getheaders())
         resp_inter = ResponseInternal(status=http_resp.status,
                                       header=headers,
                                       data=http_resp.read())
         self.request_size = self.conn.request_length
         self.response_size = len(resp_inter.data)
         if not self.is_keep_alive():
             self.conn.close()
         if self.debug:
             print(("GetResponse %s" % resp_inter))
         return resp_inter
     except Exception as e:
         self.conn.close()
         raise JrtzCloudSDKException("ClientNetworkError", str(e))
Ejemplo n.º 6
0
 def _build_req_inter(self, action, params, req_inter, options=None):
     options = options or {}
     if self.profile.signMethod == "JC1-HMAC-SHA256" or options.get(
             "IsMultipart") is True:
         self._build_req_with_jc1_signature(action, params, req_inter,
                                            options)
     elif self.profile.signMethod in ("HmacSHA1", "HmacSHA256"):
         self._build_req_with_old_signature(action, params, req_inter)
     else:
         raise JrtzCloudSDKException("ClientError",
                                     "Invalid signature method.")
 def _request(self, req_inter):
     if self.keep_alive:
         req_inter.header["Connection"] = "Keep-Alive"
     if self.debug:
         print("SendRequest %s" % req_inter)
     if req_inter.method == 'GET':
         req_inter_url = '%s?%s' % (req_inter.uri, req_inter.data)
         self.conn.request(req_inter.method, req_inter_url, None,
                           req_inter.header)
     elif req_inter.method in ['POST', 'PUT', 'PATCH', 'DELETE']:
         self.conn.request(req_inter.method, req_inter.uri, req_inter.data,
                           req_inter.header)
     else:
         raise JrtzCloudSDKException(
             "ClientParamsError",
             'Method only support (GET,POST,PUT,PATCH,DELETE)')
Ejemplo n.º 8
0
    def sign(secretKey, signStr, signMethod):
        if sys.version_info[0] > 2:
            signStr = bytes(signStr, 'utf-8')
            secretKey = bytes(secretKey, 'utf-8')

        digestmod = None
        if signMethod == 'HmacSHA256':
            digestmod = hashlib.sha256
        elif signMethod == 'HmacSHA1':
            digestmod = hashlib.sha1
        else:
            raise JrtzCloudSDKException("signMethod invalid", "signMethod only support (HmacSHA1, HmacSHA256)")

        hashed = hmac.new(secretKey, signStr, digestmod)
        base64 = binascii.b2a_base64(hashed.digest())[:-1]

        if sys.version_info[0] > 2:
            base64 = base64.decode()

        return base64
Ejemplo n.º 9
0
    def __init__(self,
                 httpProfile=None,
                 signMethod="JC1-HMAC-SHA256",
                 language="zh-CN"):
        """SDK profile.

        :param signMethod: The signature method, valid choice: HmacSHA1, HmacSHA256, JC1-HMAC-SHA256
        :type signMethod: str
        :param httpProfile: The http profile
        :type httpProfile: :class:`HttpProfile`
        :param language: Valid choice: en-US, zh-CN.
        :type language: str
        """

        self.httpProfile = HttpProfile(
        ) if httpProfile is None else httpProfile
        self.signMethod = "JC1-HMAC-SHA256" if signMethod is None else signMethod
        valid_language = ["zh-CN", "en-US"]
        if language not in valid_language:
            raise JrtzCloudSDKException(
                "ClientError",
                "Language invalid, choices: %s" % valid_language)
        self.language = language