Esempio n. 1
0
    def serialize(self):
        if self.name is None:
            raise HuaweiCloudSDKException(
                message="The parameter(name) is required")
        if not isinstance(self.name, str):
            raise HuaweiCloudSDKException(
                message="The datatype of parameter(name) "
                "is not str")

        if self.public_key is not None:
            if not isinstance(self.public_key, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(public_key) "
                    "is not str")

        if self.type is not None:
            if not isinstance(self.type, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(type) "
                    "is not str")

        if self.user_id is not None:
            if not isinstance(self.user_id, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(user_id) "
                    "is not str")

        obj = {
            "name": self.name,
            "public_key": self.public_key,
            "type": self.type,
            "user_id": self.user_id,
        }
        return util.serialize({k: v for k, v in obj.items() if v is not None})
Esempio n. 2
0
    def list_key_pair(self, user_id=None, limit=None, marker=None, **kwargs):
        """list keypairs

        :param user_id: This allows administrative users to operate key-pairs of specified user ID.
        :type user_id: str
        :param limit: Requests a page size of items.
        :type limit: int
        :param marker: The last-seen item.
        :type marker: str
        :rtype: ListKeyPairResp
        """

        query_params = []
        if user_id is not None:
            if not isinstance(user_id, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(user_id) "
                    "is not str")
            query_params.append(("user_id", user_id))

        if limit is not None:
            if not isinstance(limit, int):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(limit) "
                    "is not int")
            query_params.append(("limit", limit))

        if marker is not None:
            if not isinstance(marker, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(marker) "
                    "is not str")
            query_params.append(("marker", marker))

        header_params = {}
        header_params['Accept'] = util.select_header_accept(
            ['application/xml', 'application/json'])

        return_code, return_data, _ = self.api_client.handle_raw_request(
            'compute',
            'GET',
            '/os-keypairs',
            headers=header_params,
            query_params=query_params,
            timeout=kwargs.get('_request_timeout', None),
            _preload_content=kwargs.get('_preload_content', True))

        if return_data is not None:
            return_data = json.loads(return_data)
        else:
            return_data = {}
        if return_code not in [200]:
            raise HuaweiCloudSDKException(
                return_code, "Run list_key_pair failed, "
                "message=%s" % return_data.get("message"))
        return models.ListKeyPairResp().deserialize(return_data)
def deserialize(data, datatype, inner_class=None):
    """Deserializes dict, list, str into an object.

    :param data: data to be deserialized.
    :param datatype: datatype which the data will be deserialized to.
    :param inner_class: inner_class is a subclass of BasicModel.

    :return: object.
    """

    if data is None:
        return None

    if type(datatype) == str:
        if datatype.startswith('list['):
            sub_datatype = re.match(r"list\[(.*)\]", datatype).group(1)
            return [
                deserialize(sub_data, sub_datatype, inner_class)
                for sub_data in data
            ]

        if datatype.startswith('dict('):
            sub_datatype = re.match(r"dict\(([^,]*), (.*)\)",
                                    datatype).group(2)
            return {
                k: deserialize(v, sub_datatype, inner_class)
                for k, v in six.iteritems(data)
            }

        # convert str to class
        if datatype in NATIVE_TYPES_MAPPING:
            datatype = NATIVE_TYPES_MAPPING[datatype]
        else:
            if not (inspect.isclass(inner_class) and
                    (issubclass(inner_class, BasicModel)) and
                    (datatype == inner_class.__name__)):
                raise HuaweiCloudSDKException(
                    message="Encounter an invalid inner datatype(%s) to "
                    "desrialize data" % datatype)
            datatype = inner_class

    if datatype in PRIMITIVE_TYPES:
        return deserialize_primitive(data, datatype)
    elif datatype == object:
        return deserialize_object(data)
    elif datatype == datetime.date:
        return deserialize_date(data)
    elif datatype == datetime.datetime:
        return deserialize_datetime(data)
    elif inspect.isclass(datatype) and issubclass(datatype, BasicModel):
        return datatype().deserialize(data)

    raise HuaweiCloudSDKException(
        message="Can't deserialize data(%s) with unknown "
        "datatype(%s)" % (data, str(datatype)))
Esempio n. 4
0
    def serialize(self):
        if self.keypair is None:
            raise HuaweiCloudSDKException(
                message="The parameter(keypair) is required")
        if not isinstance(self.keypair, CreateKeyPairReqObject):
            raise HuaweiCloudSDKException(
                message="The datatype of parameter(keypair) "
                "is not CreateKeyPairReqObject")

        obj = {
            "keypair": self.keypair,
        }
        return util.serialize({k: v for k, v in obj.items() if v is not None})
Esempio n. 5
0
    def get_key_pair(self, keypair_name, user_id=None, **kwargs):
        """get a keypair

        :param keypair_name: The keypair name.
        :type keypair_name: str
        :param user_id: This allows administrative users to operate key-pairs of specified user ID.
        :type user_id: str
        :rtype: GetKeyPairResp
        """

        path_params = {}
        if not isinstance(keypair_name, str):
            raise HuaweiCloudSDKException(
                message="The datatype of parameter(keypair_name) is not "
                "str")
        path_params["keypair_name"] = quote(str(keypair_name))

        url = '/os-keypairs/{keypair_name}'.format(**path_params)

        query_params = []
        if user_id is not None:
            if not isinstance(user_id, str):
                raise HuaweiCloudSDKException(
                    message="The datatype of parameter(user_id) "
                    "is not str")
            query_params.append(("user_id", user_id))

        header_params = {}
        header_params['Accept'] = util.select_header_accept(
            ['application/xml', 'application/json'])

        return_code, return_data, _ = self.api_client.handle_raw_request(
            'compute',
            'GET',
            url,
            headers=header_params,
            query_params=query_params,
            timeout=kwargs.get('_request_timeout', None),
            _preload_content=kwargs.get('_preload_content', True))

        if return_data is not None:
            return_data = json.loads(return_data)
        else:
            return_data = {}
        if return_code not in [200]:
            raise HuaweiCloudSDKException(
                return_code, "Run get_key_pair failed, "
                "message=%s" % return_data.get("message"))
        return models.GetKeyPairResp().deserialize(return_data)
Esempio n. 6
0
    def deserialize(self, data):
        """Deserializes data into an object.

        :param data: data to be deserialized.
        :return: the instance of this class.
        """

        raise HuaweiCloudSDKException(message="Not realized function")
def check_datatype(name, param, datatype, inner_class=None):
    """Check datatype.

    :param name: the name of param
    :param param: dict, list or str.
    :param datatype: class literal, or string of class name.
    :param inner_class: inner_class is a subclass of BasicModel.
    """

    if type(datatype) == str:
        if datatype.startswith('list['):
            sub_datatype = re.match(r"list\[(.*)\]", datatype).group(1)
            for sub_data in param:
                check_datatype(name, sub_data, sub_datatype, inner_class)

        if datatype.startswith('dict('):
            sub_datatype = re.match(r"dict\(([^,]*), (.*)\)",
                                    datatype).group(2)
            for v in six.itervalues(param):
                check_datatype(name, v, sub_datatype, inner_class)

        # convert str to class
        if datatype in NATIVE_TYPES_MAPPING:
            datatype = NATIVE_TYPES_MAPPING[datatype]
        else:
            if not (inspect.isclass(inner_class) and
                    (issubclass(inner_class, BasicModel)) and
                    (datatype == inner_class.__name__)):
                raise HuaweiCloudSDKException(
                    message="Encounter an invalid inner datatype(%s) to check "
                    "datatype of parameter(%s)" % (datatype, name))

            datatype = inner_class

    try:
        if not isinstance(param, datatype):
            raise HuaweiCloudSDKException(
                message="The datatype of parameter(%s) is not %s" %
                (name, str(datatype)))
    except TypeError:
        raise HuaweiCloudSDKException(
            message="Can't check datatype of parameter(%s) with invalid "
            "datatype(%s)" % (name, str(datatype)))
Esempio n. 8
0
    def create_key_pair(self, keypair, **kwargs):
        """Add a new keypair

        :param keypair: the request parameters to create keypair
        :type keypair: CreateKeyPairReq
        :rtype: CreateKeyPairResp
        """

        if not isinstance(keypair, models.CreateKeyPairReq):
            raise HuaweiCloudSDKException(
                message="The datatype of parameter(keypair) "
                "is not CreateKeyPairReq")
        body_params = keypair.serialize()

        header_params = {}
        header_params['Accept'] = util.select_header_accept(
            ['application/xml', 'application/json'])

        header_params['Content-Type'] = util.select_header_content_type(
            ['application/json', 'application/xml'])

        return_code, return_data, _ = self.api_client.handle_raw_request(
            'compute',
            'POST',
            '/os-keypairs',
            headers=header_params,
            body=body_params,
            timeout=kwargs.get('_request_timeout', None),
            _preload_content=kwargs.get('_preload_content', True))

        if return_data is not None:
            return_data = json.loads(return_data)
        else:
            return_data = {}
        if return_code not in [200, 201]:
            raise HuaweiCloudSDKException(
                return_code, "Run create_key_pair failed, "
                "message=%s" % return_data.get("message"))
        return models.CreateKeyPairResp().deserialize(return_data)
def deserialize_datetime(data):
    """Deserializes data to datetime.

    :param data: str, it should be in iso8601 datetime format..
    :return: datetime.
    """

    if data is None:
        return None

    try:
        return date_parse(data)
    except ImportError:
        return data
    except ValueError:
        raise HuaweiCloudSDKException(
            message="Failed to parse `{0}` as datetime object".format(data))
Esempio n. 10
0
def deserialize_date(data):
    """Deserializes data to date.

    :param data: str.
    :return: date.
    """

    if data is None:
        return None

    try:
        return date_parse(data).date()
    except ImportError:
        return data
    except ValueError:
        raise HuaweiCloudSDKException(
            message="Failed to parse `{0}` as date object".format(data))
Esempio n. 11
0
def deserialize_primitive(data, datatype):
    """Deserializes string to primitive type.

    :param data: str.
    :param datatype: class literal.

    :return: int, long, float, str, bool.
    """

    if data is None:
        return None

    try:
        return datatype(data)
    except UnicodeEncodeError:
        return six.text_type(data)
    except TypeError:
        raise HuaweiCloudSDKException(
            message="Deserialize data(%s) with unmatched datatype(%s)" %
            (data, str(datatype)))
Esempio n. 12
0
def serialize(obj):
    """Builds a JSON POST object.

    :param obj: The data to serialize.
    :return: The serialized form of data.
    """

    if obj is None:
        return None
    elif isinstance(obj, PRIMITIVE_TYPES):
        return obj
    elif isinstance(obj, (datetime.datetime, datetime.date)):
        return obj.isoformat()
    elif isinstance(obj, BasicModel):
        return obj.serialize()
    elif isinstance(obj, dict):
        return {k: serialize(v) for k, v in six.iteritems(obj)}
    elif isinstance(obj, list):
        return [serialize(sub_obj) for sub_obj in obj]
    elif isinstance(obj, tuple):
        return tuple(serialize(sub_obj) for sub_obj in obj)

    raise HuaweiCloudSDKException(
        message="Can't serialize object with unknown datatype(%s)" % type(obj))
Esempio n. 13
0
    def serialize(self):
        """Builds a JSON POST object."""

        raise HuaweiCloudSDKException(message="Not realized function")