Skip to content
Myr

Fix inconsistent exception type in response.json() method (#5856)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Steve Berdy · committed by GitHub · parent 941a77f · Browse files · 7 files+47 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+47 added−18 removed

  • tests:+6 added−1 removed
  • other:+41 added−17 removed

7 files+47 added−18 removed

modified:docs/user/quickstart.rst+3 added-3 removed
151 unmodified lines
152 [{'repository': {'open_issues': 0, 'url': 'https://github.com/...153154In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if155the response gets a 204 (No Content), or if the response contains invalid JSON,156attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is157installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or158``json.JSONDecodeError`` on Python 3.156attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception157provides interoperability for multiple exceptions that may be thrown by different158python versions and json serialization libraries.159160It should be noted that the success of the call to ``r.json()`` does **not**161indicate the success of the response. Some servers may return a JSON object in a162failed response (e.g. error details with HTTP 500). Such JSON will be decoded
407 unmodified lines
modified:requests/__init__.py+1 added-1 removed
137 unmodified lines
138from .status_codes import codes139from .exceptions import (140 RequestException, Timeout, URLRequired,141 TooManyRedirects, HTTPError, ConnectionError,142 FileModeWarning, ConnectTimeout, ReadTimeout142 FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError143)144145# Set default logging handler to avoid "No handler found" warnings.146import logging
6 unmodified lines
modified:requests/compat.py+7 added-1 removed
26 unmodified lines
2728#: Python 3.x?29is_py3 = (_ver[0] == 3)3031has_simplejson = False32try:33 import simplejson as json34 has_simplejson = True35except ImportError:36 import json3738# ---------
11 unmodified lines
50 from StringIO import StringIO51 # Keep OrderedDict for backwards compatibility.52 from collections import Callable, Mapping, MutableMapping, OrderedDict535254 builtin_str = str55 bytes = str56 str = unicode57 basestring = basestring58 numeric_types = (int, long, float)59 integer_types = (int, long)60 JSONDecodeError = ValueError6162elif is_py3:63 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag64 from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
2 unmodified lines
67 from io import StringIO68 # Keep OrderedDict for backwards compatibility.69 from collections import OrderedDict70 from collections.abc import Callable, Mapping, MutableMapping71 if has_simplejson:72 from simplejson import JSONDecodeError73 else:74 from json import JSONDecodeError7576 builtin_str = str77 str = str78 bytes = bytes
3 unmodified lines
modified:requests/exceptions.py+6 added
6 unmodified lines
7This module contains the set of Requests' exceptions.8"""9from urllib3.exceptions import HTTPError as BaseHTTPError1011from .compat import JSONDecodeError as CompatJSONDecodeError121314class RequestException(IOError):15 """There was an ambiguous exception that occurred while handling your16 request.17 """
12 unmodified lines
30class InvalidJSONError(RequestException):31 """A JSON error occurred."""323334class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):35 """Couldn't decode the text into json"""363738class HTTPError(RequestException):39 """An HTTP error occurred."""4041
92 unmodified lines
modified:requests/models.py+18 added-11 removed
27 unmodified lines
28from .auth import HTTPBasicAuth29from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar30from .exceptions import (31 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,32 ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError)32 ContentDecodingError, ConnectionError, StreamConsumedError,33 InvalidJSONError)34from .exceptions import JSONDecodeError as RequestsJSONDecodeError35from ._internal_utils import to_native_string, unicode_is_ascii36from .utils import (37 guess_filename, get_auth_from_url, requote_uri,38 stream_decode_response_unicode, to_key_val_list, parse_header_links,39 iter_slices, guess_json_utf, super_len, check_header_validity)40from .compat import (41 Callable, Mapping,42 cookielib, urlunparse, urlsplit, urlencode, str, bytes,41 is_py2, chardet, builtin_str, basestring)43 is_py2, chardet, builtin_str, basestring, JSONDecodeError)44from .compat import json as complexjson45from .status_codes import codes4647#: The set of HTTP status codes that indicate an automatically
421 unmodified lines
469 # provides this natively, but Python 3 gives a Unicode string.470 content_type = 'application/json'471472 try:471 body = complexjson.dumps(json, allow_nan=False)473 body = complexjson.dumps(json, allow_nan=False)474 except ValueError as ve:473 raise InvalidJSONError(ve, request=self)475 raise InvalidJSONError(ve, request=self)476477 if not isinstance(body, bytes):478 body = body.encode('utf-8')479
403 unmodified lines
883 def json(self, **kwargs):884 r"""Returns the json-encoded content of a response, if any.885886 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.885 :raises simplejson.JSONDecodeError: If the response body does not886 contain valid json and simplejson is installed.887 :raises json.JSONDecodeError: If the response body does not contain888 valid json and simplejson is not installed on Python 3.889 :raises ValueError: If the response body does not contain valid890 json and simplejson is not installed on Python 2. 887 :raises requests.exceptions.JSONDecodeError: If the response body does not888 contain valid json.889 """890891 if not self.encoding and self.content and len(self.content) > 3:892 # No encoding set. JSON RFC 4627 section 3 states we should expect
11 unmodified lines
904 # but some other 8-bit codec. This is an RFC violation,905 # and the server didn't bother to tell us what codec *was*906 # used.907 pass910 return complexjson.loads(self.text, **kwargs)908909 try:910 return complexjson.loads(self.text, **kwargs)911 except JSONDecodeError as e:912 # Catch JSON-related errors and raise as requests.JSONDecodeError913 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError914 if is_py2: # e is a ValueError915 raise RequestsJSONDecodeError(e.message)916 else:917 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)918919 @property920 def links(self):921 """Returns the parsed header links of the response, if any."""922
51 unmodified lines
modified:tests/test_requests.py+6 added-1 removed
2568 unmodified lines
25692570 def test_post_json_nan(self, httpbin):2571 data = {"foo": float("nan")}2572 with pytest.raises(requests.exceptions.InvalidJSONError):2573 r = requests.post(httpbin('post'), json=data)2573 r = requests.post(httpbin('post'), json=data)25742575 def test_json_decode_compatibility(self, httpbin):2576 r = requests.get(httpbin('bytes/20'))2577 with pytest.raises(requests.exceptions.JSONDecodeError):2578 r.json()
modified:HISTORY.md+6 added-1 removed
2 unmodified lines
34dev5---67- \[Short description of non-trivial change.\]7- \[Short description of non-trivial change.\]89- Added a `requests.exceptions.JSONDecodeError` to decrease inconsistencies10 in the library. This gets raised in the `response.json()` method, and is11 backwards compatible as it inherits from previously thrown exceptions.12 Can be caught from `requests.exceptions.RequestException` as well.13142.26.0 (2021-07-13)15-------------------1617**Improvements**
1739 unmodified lines