Beispiel #1
0
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)
Beispiel #2
0
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)
Beispiel #3
0
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 chart_studio.api.v2.utils.request for examples on how to do this.
        raise _plotly_utils.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
Beispiel #4
0
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 _plotly_utils.exceptions.PlotlyError(
                "Cannot supply data and json kwargs."
            )
        kwargs["data"] = _json.dumps(
            kwargs.pop("json"), sort_keys=True, cls=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
Beispiel #5
0
 def test_sign_in_cannot_validate(self):
     self.users_current_mock.side_effect = exceptions.PlotlyRequestError(
         "msg", 400, "foobar")
     with self.assertRaisesRegex(_plotly_utils.exceptions.PlotlyError,
                                 "Sign in failed"):
         py.sign_in("foo", "bar")
Beispiel #6
0
 def test_sign_in_cannot_validate(self):
     self.users_current_mock.side_effect = exceptions.PlotlyRequestError(
         'msg', 400, 'foobar')
     with self.assertRaisesRegexp(_plotly_utils.exceptions.PlotlyError,
                                  'Sign in failed'):
         py.sign_in('foo', 'bar')