def _parse_and_handle_errors( response ) -> Union[MutableMapping[str, Any], List[MutableMapping[str, Any]]]: """Handle response""" message = "Unknown error" if response.headers.get( "content-type" ) == "application/json;charset=utf-8" and response.status_code != HTTPStatus.OK: message = response.json().get("message") if response.status_code == HTTPStatus.FORBIDDEN: raise HubspotAccessDenied(message, response=response) elif response.status_code in (HTTPStatus.UNAUTHORIZED, CLOUDFLARE_ORIGIN_DNS_ERROR): raise HubspotInvalidAuth(message, response=response) elif response.status_code == HTTPStatus.TOO_MANY_REQUESTS: retry_after = response.headers.get("Retry-After") raise HubspotRateLimited( f"429 Rate Limit Exceeded: API rate-limit has been reached until {retry_after} seconds." " See https://developers.hubspot.com/docs/api/usage-details", response=response, ) elif response.status_code in (HTTPStatus.BAD_GATEWAY, HTTPStatus.SERVICE_UNAVAILABLE): raise HubspotTimeout(message, response=response) else: response.raise_for_status() return response.json()
def _parse_and_handle_errors( response ) -> Union[MutableMapping[str, Any], List[MutableMapping[str, Any]]]: """Handle response""" message = "Unknown error" if response.headers.get( "content-type" ) == "application/json;charset=utf-8" and response.status_code != 200: message = response.json().get("message") if response.status_code == 403: raise HubspotAccessDenied(message, response=response) elif response.status_code == 401: raise HubspotInvalidAuth(message, response=response) elif response.status_code == 429: retry_after = response.headers.get("Retry-After") raise HubspotRateLimited( f"429 Rate Limit Exceeded: API rate-limit has been reached until {retry_after} seconds." " See https://developers.hubspot.com/docs/api/usage-details", response=response, ) elif response.status_code in (502, 504): raise HubspotTimeout(message, response=response) else: response.raise_for_status() return response.json()
def _acquire_access_token_from_refresh_token(self): payload = { "grant_type": "refresh_token", "redirect_uri": self._credentials["redirect_uri"], "refresh_token": self._credentials["refresh_token"], "client_id": self._credentials["client_id"], "client_secret": self._credentials["client_secret"], } resp = requests.post(self.BASE_URL + "/oauth/v1/token", data=payload) if resp.status_code == HTTPStatus.FORBIDDEN: raise HubspotInvalidAuth(resp.content, response=resp) resp.raise_for_status() auth = resp.json() self._credentials["access_token"] = auth["access_token"] self._credentials["refresh_token"] = auth["refresh_token"] self._credentials["token_expires"] = datetime.utcnow() + timedelta( seconds=auth["expires_in"] - 600) logger.info("Token refreshed. Expires at %s", self._credentials["token_expires"])