Use a JSON-specific encoding detection when no encoding has been specified.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
JSON *must* be encoded using UTF-8, UTF-16 or UTF-32 (see the [RFC][1]; detect the encoding based on the fact that JSON always starts with 2 ASCII characters. [1]: http://tools.ietf.org/html/rfc4627#section-3
authored by Martijn Pieters · committed by Martijn Pieters · parent 6e0ad1e · Browse files · 3 files·+102 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
3 files+102 added−1 removed
- tests:+53 added−0 removed
- other:+49 added−1 removed
Provenance
- Commit
4decc79- Tree
2f2cc59- Author
Martijn Pieters <mj@zopatista.com>- Committer
Martijn Pieters <mj@zopatista.com>- Parent
6e0ad1e
3 files changed+102 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)39 802 unmodified lines842 843 @property844 def json(self):845 """Returns the json-encoded content of a response, if any."""846+847+ if not self.encoding and len(self.content) > 3:848+ # No encoding set. JSON RFC 4627 section 3 states we should expect849+ # UTF-8, -16 or -32. Detect which one to use; If the detection or850+ # decoding fails, fall back to `self.text` (using chardet to make851+ # a best guess).852+ encoding = guess_json_utf(self.content)853+ if encoding is not None:854+ try:855+ return json.loads(self.content.decode(encoding))856+ except (ValueError, UnicodeDecodeError):857+ pass858 try:859 return json.loads(self.text or self.content)860 except ValueError:861 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+53 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+import os5+import sys6+import unittest7+import random8+9+# Path hack.10+sys.path.insert(0, os.path.abspath('..'))11+import requests.utils12+from requests.compat import is_py3, bytes13+14+15+class GuessJSONUTFTests(unittest.TestCase):16+ """Smoke test for https functionality."""17+18+ codecs = (19+ 'utf-8', 'utf-8-sig',20+ 'utf-16', 'utf-16-le', 'utf-16-be',21+ 'utf-32', 'utf-32-le', 'utf-32-be'22+ )23+24+ def test_guess_encoding(self):25+ # Throw 4-character ASCII strings (encoded to a UTF encoding)26+ # at the guess routine; it should correctly guess all codecs.27+ unichr = chr if is_py3 else __builtins__.unichr28+ guess = requests.utils.guess_json_utf29+ for c in range(33, 127): # printable only30+ sample = unichr(c) * 431+ for codec in self.codecs:32+ res = guess(sample.encode(codec))33+ self.assertEqual(res, codec)34+35+ def test_smoke_encoding(self):36+ # Throw random 4-byte strings at the guess function.37+ # Any guess for a UTF encoding is verified, a decode exception38+ # is a test failure.39+ chr = (lambda c: bytes([c])) if is_py3 else __builtins__.chr40+ guess = requests.utils.guess_json_utf41+ for i in range(1000):42+ sample = bytes().join(43+ [chr(random.randrange(256)) for _ in range(4)])44+ res = guess(sample)45+ if res is not None and res != 'utf-8':46+ # This should decode without errors if this is *really*47+ # something in this encoding. Skip UTF-8, it is more48+ # picky about valid data.49+ sample.decode(res)50+51+52+if __name__ == '__main__':53+ unittest.main()