Merge pull request #909 from mjpieters/issue765-json-encodings
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Use a JSON-specific encoding detection when no encoding has been specified
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 2c9bee2, e26ccb3 · Browse files · 4 files·+127 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+127 added−1 removed
- tests:+77 added−0 removed
- other:+50 added−1 removed
Provenance
- Commit
28dc725- Tree
6cce0eb- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
2c9bee2- Parent 2
e26ccb3
4 files changed+127 added−1 removed
modified:requests/models.py+14 added-1 removed
29 unmodified lines30 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)31 from .utils import (32 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,33 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,34- to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)34+ to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices,35+ guess_json_utf)36 from .compat import (37 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,38 StringIO, is_py2, chardet, json, builtin_str, urldefrag)39 804 unmodified lines844 845 @property846 def json(self):847 """Returns the json-encoded content of a response, if any."""848+849+ if not self.encoding and len(self.content) > 3:850+ # No encoding set. JSON RFC 4627 section 3 states we should expect851+ # UTF-8, -16 or -32. Detect which one to use; If the detection or852+ # decoding fails, fall back to `self.text` (using chardet to make853+ # a best guess).854+ encoding = guess_json_utf(self.content)855+ if encoding is not None:856+ try:857+ return json.loads(self.content.decode(encoding))858+ except (ValueError, UnicodeDecodeError):859+ pass860 try:861 return json.loads(self.text or self.content)862 except ValueError:863 return None44 unmodified linesmodified:requests/utils.py+35 added
577 unmodified lines578 579 links.append(link)580 581 return links582+583+584+# Null bytes; no need to recreate these on each call to guess_json_utf585+_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3586+_null2 = _null * 2587+_null3 = _null * 3588+589+590+def guess_json_utf(data):591+ # JSON always starts with two ASCII characters, so detection is as592+ # easy as counting the nulls and from their location and count593+ # determine the encoding. Also detect a BOM, if present.594+ sample = data[:4]595+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE):596+ return 'utf-32' # BOM included597+ if sample[:3] == codecs.BOM_UTF8:598+ return 'utf-8-sig' # BOM included, MS style (discouraged)599+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):600+ return 'utf-16' # BOM included601+ nullcount = sample.count(_null)602+ if nullcount == 0:603+ return 'utf-8'604+ if nullcount == 2:605+ if sample[::2] == _null2: # 1st and 3rd are null606+ return 'utf-16-be'607+ if sample[1::2] == _null2: # 2nd and 4th are null608+ return 'utf-16-le'609+ # Did not detect 2 valid UTF-16 ascii-range characters610+ if nullcount == 3:611+ if sample[:3] == _null3:612+ return 'utf-32-be'613+ if sample[1:] == _null3:614+ return 'utf-32-le'615+ # Did not detect a valid UTF-32 ascii-range character616+ return Noneadded:tests/test_utils.py+77 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+import codecs5+import os6+import sys7+import unittest8+import random9+10+# Path hack.11+sys.path.insert(0, os.path.abspath('..'))12+import requests.utils13+from requests.compat import is_py3, bytes14+15+16+if is_py3:17+ unichr = chr18+ byteschr = lambda c: bytes([c])19+else:20+ byteschr = chr21+22+23+class GuessJSONUTFTests(unittest.TestCase):24+ """Tests for the JSON UTF encoding guessing code."""25+26+ codecs = (27+ 'utf-8', 'utf-8-sig',28+ 'utf-16', 'utf-16-le', 'utf-16-be',29+ 'utf-32', 'utf-32-le', 'utf-32-be'30+ )31+32+ def test_guess_encoding(self):33+ # Throw 4-character ASCII strings (encoded to a UTF encoding)34+ # at the guess routine; it should correctly guess all codecs.35+ guess = requests.utils.guess_json_utf36+ for c in range(33, 127): # printable only37+ sample = unichr(c) * 438+ for codec in self.codecs:39+ res = guess(sample.encode(codec))40+ self.assertEqual(res, codec)41+42+ def test_smoke_encoding(self):43+ # Throw random 4-byte strings at the guess function.44+ # Any guess for a UTF encoding is verified, a decode exception45+ # is a test failure.46+ guess = requests.utils.guess_json_utf47+ for i in range(1000):48+ sample = bytes().join(49+ [byteschr(random.randrange(256)) for _ in range(4)])50+ res = guess(sample)51+ if res is not None:52+ # This should decode without errors if this is *really*53+ # something in this encoding. However, UTF-8 is a lot54+ # more picky, so we expect errors there. UTF-16 surrogate55+ # pairs also fail56+ try:57+ sample.decode(res)58+ except UnicodeDecodeError as e:59+ self.assertEqual(e.args[0].replace('-', '').lower(),60+ res.replace('-', '').lower())61+ if res == 'utf-8':62+ self.assertTrue(e.args[-1], (63+ 'invalid continuation byte',64+ 'invalid start byte'))65+ continue66+ if res == 'utf-16':67+ self.assertEqual(e.args[-1], 'unexpected end of data')68+ self.assertTrue(sample[:2] in (69+ codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))70+ # the second two bytes are in the range \ud800-\udfff71+ # if someone wants to add tests for that as well. I don't72+ # see the need; we are not testing UTF decoding here.73+ continue74+ raise75+76+if __name__ == '__main__':77+ unittest.main()modified:AUTHORS.rst+1 added
113 unmodified lines114 - Ian Cordasco <graffatcolmingov@gmail.com> @sigmavirus24115 - Rhys Elsmore116 - André Graf (dergraf)117 - Stephen Zhuang (everbird)118+- Martijn Pieters