Skip to content
Myr

Reinstate falling back to self.text for JSON responses

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

A JSON response that has no encoding specified will be decoded with a detected UTF codec (compliant with the JSON RFC), but if that fails, we guessed wrong and need to fall back to charade character detection (via `self.text`). Kenneth removed this functionality (by accident?) in 1451ba0c6d395c41f86da35036fa361c3a41bc90, this reinstates it again and adds a log warning. Fixes #1674

authored by Martijn Pieters · committed by Martijn Pieters · parent 0b68037 · Browse files · 1 file+11 added−2 removed
This commit

State

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

Diff stats

1 file+11 added−2 removed

  • other:+11 added−2 removed

1 file+11 added−2 removed

modified:requests/models.py+11 added-2 removed
723 unmodified lines
724725 if not self.encoding and len(self.content) > 3:726 # No encoding set. JSON RFC 4627 section 3 states we should expect727 # UTF-8, -16 or -32. Detect which one to use; If the detection or728 # decoding fails, fall back to `self.text` (using chardet to make728 # decoding fails, fall back to `self.text` (using charade to make729 # a best guess).730 encoding = guess_json_utf(self.content)731 if encoding is not None:732 try:732 return json.loads(self.content.decode(encoding), **kwargs)733 return json.loads(self.content.decode(encoding), **kwargs)734 except UnicodeDecodeError:735 # Wrong UTF codec detected; usually because it's not UTF-8736 # but some other 8-bit codec. This is an RFC violation,737 # and the server didn't bother to tell us what codec *was*738 # used.739 pass740 log.warn('No encoding specified for JSON response, and no '741 'UTF codec detected. Falling back to charade best guess.')742 return json.loads(self.text, **kwargs)743744 @property745 def links(self):
37 unmodified lines