def validate_response(response): """ Raise a helpful PlotlyRequestError for failed requests. :param (requests.Response) response: A Response object from an api request. :raises: (PlotlyRequestError) If the request failed for any reason. :returns: (None) """ if response.ok: return content = response.content status_code = response.status_code try: parsed_content = response.json() except ValueError: message = content if content else 'No Content' raise exceptions.PlotlyRequestError(message, status_code, content) message = '' if isinstance(parsed_content, dict): errors = parsed_content.get('errors', []) messages = [error.get('message') for error in errors] message = '\n'.join([msg for msg in messages if msg]) if not message: message = content if content else 'No Content' raise exceptions.PlotlyRequestError(message, status_code, content)
def validate_response(response): """ Raise a helpful PlotlyRequestError for failed requests. :param (requests.Response) response: A Response object from an api request. :raises: (PlotlyRequestError) If the request failed for any reason. :returns: (None) """ content = response.content status_code = response.status_code try: parsed_content = response.json() except ValueError: message = content if content else 'No Content' raise exceptions.PlotlyRequestError(message, status_code, content) message = '' if isinstance(parsed_content, dict): error = parsed_content.get('error') if error: message = error else: if response.ok: return if not message: message = content if content else 'No Content' raise exceptions.PlotlyRequestError(message, status_code, content)
def request(method, url, **kwargs): """ Central place to make any v1 api request. :param (str) method: The request method ('get', 'put', 'delete', ...). :param (str) url: The full api url to make the request to. :param kwargs: These are passed along to requests. :return: (requests.Response) The response directly from requests. """ if kwargs.get('json', None) is not None: # See plotly.api.v2.utils.request for examples on how to do this. raise exceptions.PlotlyError('V1 API does not handle arbitrary json.') kwargs['headers'] = dict(kwargs.get('headers', {}), **get_headers()) kwargs['verify'] = config.get_config()['plotly_ssl_verification'] try: response = requests.request(method, url, **kwargs) except RequestException as e: # The message can be an exception. E.g., MaxRetryError. message = str(getattr(e, 'message', 'No message')) response = getattr(e, 'response', None) status_code = response.status_code if response else None content = response.content if response else 'No content' raise exceptions.PlotlyRequestError(message, status_code, content) validate_response(response) return response
def response_handler(cls, response): try: response.raise_for_status() except requests.exceptions.HTTPError as requests_exception: plotly_exception = exceptions.PlotlyRequestError(requests_exception) raise(plotly_exception) if ('content-type' in response.headers and 'json' in response.headers['content-type'] and len(response.content) > 0): response_dict = json.loads(response.content.decode('utf8')) if 'warnings' in response_dict and len(response_dict['warnings']): warnings.warn('\n'.join(response_dict['warnings'])) return response_dict
def request(method, url, **kwargs): """ Central place to make any api v2 api request. :param (str) method: The request method ('get', 'put', 'delete', ...). :param (str) url: The full api url to make the request to. :param kwargs: These are passed along (but possibly mutated) to requests. :return: (requests.Response) The response directly from requests. """ kwargs['headers'] = dict(kwargs.get('headers', {}), **get_headers()) # Change boolean params to lowercase strings. E.g., `True` --> `'true'`. # Just change the value so that requests handles query string creation. if isinstance(kwargs.get('params'), dict): kwargs['params'] = kwargs['params'].copy() for key in kwargs['params']: if isinstance(kwargs['params'][key], bool): kwargs['params'][key] = _json.dumps(kwargs['params'][key]) # We have a special json encoding class for non-native objects. if kwargs.get('json') is not None: if kwargs.get('data'): raise exceptions.PlotlyError('Cannot supply data and json kwargs.') kwargs['data'] = _json.dumps(kwargs.pop('json'), sort_keys=True, cls=utils.PlotlyJSONEncoder) # The config file determines whether reuqests should *verify*. kwargs['verify'] = config.get_config()['plotly_ssl_verification'] try: response = requests.request(method, url, **kwargs) except RequestException as e: # The message can be an exception. E.g., MaxRetryError. message = str(getattr(e, 'message', 'No message')) response = getattr(e, 'response', None) status_code = response.status_code if response else None content = response.content if response else 'No content' raise exceptions.PlotlyRequestError(message, status_code, content) validate_response(response) return response
def test_sign_in_cannot_validate(self): self.users_current_mock.side_effect = exceptions.PlotlyRequestError( 'msg', 400, 'foobar') with self.assertRaisesRegexp(exceptions.PlotlyError, 'Sign in failed'): py.sign_in('foo', 'bar')