Skip to content
Myr

Fix #6628 - JSONDecodeError are not deserializable

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

requests.exceptions.JSONDecodeError are not deserializable: calling `pickle.dumps` followed by `pickle.loads` will trigger an error. This is particularly a problem in a process pool, as an attempt to decode json on an invalid json document will result in the entire process pool crashing. This is due to the MRO of the `requests.exceptions.JSONDecodeError` class: the `__reduce__` method called when pickling an instance is not the one from the JSON library parent: two out of three args expected for instantiation will be dropped, and the instance can't be deserialised. By specifying in the class which parent `__reduce__` method should be called, the bug is fixed as all args are carried over in the resulting pickled bytes.

authored by Thomas Dehghani · committed by Thomas Dehghani · parent 96b22fa · Browse files · 2 files+20 added−0 removed
This commit

State

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

Diff stats

2 files+20 added−0 removed

  • tests:+10 added−0 removed
  • other:+10 added−0 removed

2 files+20 added−0 removed

modified:src/requests/exceptions.py+10 added
39 unmodified lines
40 """41 CompatJSONDecodeError.__init__(self, *args)42 InvalidJSONError.__init__(self, *self.args, **kwargs)4344 def __reduce__(self):45 """46 The __reduce__ method called when pickling the object must47 be the one from the JSONDecodeError (be it json/simplejson)48 as it expects all the arguments for instantiation, not just49 one like the IOError, and the MRO would by default call the50 __reduce__ method from the IOError due to the inheritance order.51 """52 return CompatJSONDecodeError.__reduce__(self)535455class HTTPError(RequestException):56 """An HTTP error occurred."""5758
93 unmodified lines
modified:tests/test_requests.py+10 added
2808 unmodified lines
2809 assert r3 == 4252810 assert r4 == 4252811 assert r5 == 4252812 assert r6 == 425281328142815def test_json_decode_errors_are_serializable_deserializable():2816 json_decode_error = requests.exceptions.JSONDecodeError(2817 "Extra data",2818 '{"responseCode":["706"],"data":null}{"responseCode":["706"],"data":null}',2819 36,2820 )2821 deserialized_error = pickle.loads(pickle.dumps(json_decode_error))2822 assert repr(json_decode_error) == repr(deserialized_error)