Ejemplo n.º 1
0
    def __validate_inputs(self, kwargs):
        for param in self.params_map["enum"]:
            if param in kwargs:
                check_allowed_values(self.allowed_values, (param, ),
                                     kwargs[param])

        for param in self.params_map["validation"]:
            if param in kwargs:
                check_validations(self.validations, (param, ),
                                  kwargs[param],
                                  configuration=self.api_client.configuration)

        if kwargs["_check_input_type"] is False:
            return

        for key, value in kwargs.items():
            fixed_val = validate_and_convert_types(
                value,
                self.openapi_types[key],
                [key],
                False,
                kwargs["_check_input_type"],
                configuration=self.api_client.configuration,
            )
            kwargs[key] = fixed_val
def create_handler(
    session: Optional[SessionProxy],
    request: ResourceHandlerRequest,
    callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
    LOG.info("Starting %s Create Handler", TYPE_NAME)
    model = request.desiredResourceState

    try:
        json_payload = json.loads(model.DashboardDefinition)
    except json.JSONDecodeError as e:
        LOG.error("Exception when loading the Dashboard JSON definition: %s\n",
                  e)
        return ProgressEvent(
            status=OperationStatus.FAILED,
            resourceModel=model,
            message=f"Error loading Dashboard JSON definition: {e}")

    with v1_client(
            model.DatadogCredentials.ApiKey,
            model.DatadogCredentials.ApplicationKey,
            model.DatadogCredentials.ApiURL,
            TELEMETRY_TYPE_NAME,
            __version__,
    ) as api_client:
        api_instance = DashboardsApi(api_client)
        try:
            # Call the deserialization function of the python client.
            # It expects the loaded JSON payload, the python client type of the model,
            # some path to the data (not sure what this one does),
            # whether or not the payload is a server payload, so true in our case,
            # whether or not to do type conversion, true in our case too
            # and importantly the api_client configuration, needed to perform the type conversions
            dashboard = validate_and_convert_types(
                json_payload, (Dashboard, ), ["resource_data"],
                True,
                True,
                configuration=api_client.configuration)
            res = api_instance.create_dashboard(dashboard)
            model.Id = res.id
        except TypeError as e:
            LOG.error(
                "Exception when deserializing the Dashboard payload definition: %s\n",
                e)
            return ProgressEvent(status=OperationStatus.FAILED,
                                 resourceModel=model,
                                 message=f"Error deserializing dashboard: {e}")
        except ApiException as e:
            LOG.error(
                "Exception when calling DashboardsApi->create_dashboard: %s\n",
                e)
            return ProgressEvent(status=OperationStatus.FAILED,
                                 resourceModel=model,
                                 message=f"Error creating dashboard: {e}")
    return read_handler(session, request, callback_context)
    def deserialize(self, response, response_type, _check_type):
        """Deserializes response into an object.

        :param response: RESTResponse object to be deserialized.
        :param response_type: For the response, a tuple containing:
            valid classes
            a list containing valid classes (for list schemas)
            a dict containing a tuple of valid classes as the value
            Example values:
            (str,)
            (Pet,)
            (float, none_type)
            ([int, none_type],)
            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
        :param _check_type: boolean, whether to check the types of the data
            received from the server
        :type _check_type: bool

        :return: deserialized object.
        """
        # handle file downloading
        # save response body into a tmp file and return the instance
        if response_type == (file_type, ):
            content_disposition = response.getheader("Content-Disposition")
            return deserialize_file(response.data,
                                    self.configuration,
                                    content_disposition=content_disposition)

        # fetch data from response object
        try:
            received_data = json.loads(response.data)
        except ValueError:
            received_data = response.data

        # store our data under the key of 'received_data' so users have some
        # context if they are deserializing a string and the data type is wrong
        deserialized_data = validate_and_convert_types(
            received_data,
            response_type, ['received_data'],
            True,
            _check_type,
            configuration=self.configuration)
        return deserialized_data