How to use the dnacentersdk.exceptions.ApiError function in dnacentersdk

To help you get started, we’ve selected a few dnacentersdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cisco-en-programmability / dnacentersdk / tests / test_dnacentersdk.py View on Github external
def test_custom_base_url(self):
        custom_url = "https://custom.domain.com/v1/"
        with pytest.raises(dnacentersdk.exceptions.ApiError):
            dnacentersdk.DNACenterAPI(username=DNA_CENTER_USERNAME,
                                      password=DNA_CENTER_PASSWORD,
                                      encoded_auth=DNA_CENTER_ENCODED_AUTH,
                                      base_url=custom_url,
                                      verify=DEFAULT_VERIFY,
                                      version=DNA_CENTER_VERSION)
github cisco-en-programmability / dnacentersdk / dnacentersdk / restsession.py View on Github external
else:
                    raise dnacentersdkException('IOError {}'.format(e))
            try:
                # Check the response code for error conditions
                check_response_code(response, erc)
            except RateLimitError as e:
                # Catch rate-limit errors
                # Wait and retry if automatic rate-limit handling is enabled
                if self.wait_on_rate_limit:
                    warnings.warn(RateLimitWarning(response))
                    time.sleep(e.retry_after)
                    continue
                else:
                    # Re-raise the RateLimitError
                    raise
            except ApiError as e:
                if e.status_code == 401 and custom_refresh < 1:
                    logger.debug(pprint_response_info(response))
                    logger.debug('Refreshing access token')
                    self.refresh_token()
                    logger.debug('Refreshed token.')
                    return self.request(method, url, erc, 1, **kwargs)
                else:
                    # Re-raise the ApiError
                    logger.debug(pprint_response_info(response))
                    raise
            else:
                logger.debug(pprint_response_info(response))
                return response
github cisco-en-programmability / dnacentersdk / dnacentersdk / utils.py View on Github external
response(requests.response): The response object returned by a request
            using the requests package.
        expected_response_code(int): The expected response code (HTTP response
            code).

    Raises:
        ApiError: If the requests.response.status_code does not match the
            provided expected response code (erc).

     """
    if response.status_code in expected_response_code:
        pass
    elif response.status_code == RATE_LIMIT_RESPONSE_CODE:
        raise RateLimitError(response)
    else:
        raise ApiError(response)
github cisco-en-programmability / dnacentersdk / dnacentersdk / exceptions.py View on Github external
super(ApiError, self).__init__(
            "[{status_code}]{status} - {message}".format(
                status_code=self.status_code,
                status=" " + self.status if self.status else "",
                message=self.message or self.description or "Unknown Error",
            )
        )

    def __repr__(self):
        return "<{exception_name} [{status_code}]>".format(
            exception_name=self.__class__.__name__,
            status_code=self.status_code,
        )


class RateLimitError(ApiError):
    """DNA Center Rate-Limit exceeded Error.

    Raised when a rate-limit exceeded message is received and the request
    **will not** be retried.
    """

    def __init__(self, response):
        assert isinstance(response, requests.Response)

        # Extended exception attributes
        self.retry_after = max(1, int(response.headers.get('Retry-After', 15)))
        """The `Retry-After` time period (in seconds) provided by DNA Center.

        Defaults to 15 seconds if the response `Retry-After` header isn't
        present in the response headers, and defaults to a minimum wait time of
        1 second if DNA Center returns a `Retry-After` header of 0 seconds.
github cisco-en-programmability / dnacentersdk / dnacentersdk / exceptions.py View on Github external
if "application/json" in \
                self.response.headers.get("Content-Type", "").lower():
            try:
                self.details = self.response.json()
            except ValueError:
                logger.warning("Error parsing JSON response body")

        self.message = self.details.get("message") or\
            self.details.get("response", {}).get("message")\
            if self.details else None
        """The error message from the parsed API response."""

        self.description = RESPONSE_CODES.get(self.status_code)
        """A description of the HTTP Response Code from the API docs."""

        super(ApiError, self).__init__(
            "[{status_code}]{status} - {message}".format(
                status_code=self.status_code,
                status=" " + self.status if self.status else "",
                message=self.message or self.description or "Unknown Error",
            )