Merge pull request #2695 from pallets/backport-2691-json-encoding
Before adoption: this commit came in with the history the project adopted, so no landing records it.
detect UTF encodings when loading json
authored by David Lord · committed by GitHub · parents aab4c8c, 0e1e9a0 · Browse files · 3 files·+67 added−23 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+67 added−23 removed
- tests:+16 added−12 removed
- other:+51 added−11 removed
Provenance
- Commit
b178e89- Tree
b674781- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
aab4c8c- Parent 2
0e1e9a0
3 files changed+67 added−23 removed
modified:flask/json.py+48 added-1 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import codecs12 import io13 import uuid14 from datetime import date15 from .globals import current_app, request92 unmodified lines108 else:109 kwargs.setdefault('cls', JSONDecoder)110 111 112+def detect_encoding(data):113+ """Detect which UTF codec was used to encode the given bytes.114+115+ The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is116+ accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big117+ or little endian. Some editors or libraries may prepend a BOM.118+119+ :param data: Bytes in unknown UTF encoding.120+ :return: UTF encoding name121+ """122+ head = data[:4]123+124+ if head[:3] == codecs.BOM_UTF8:125+ return 'utf-8-sig'126+127+ if b'\x00' not in head:128+ return 'utf-8'129+130+ if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):131+ return 'utf-32'132+133+ if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):134+ return 'utf-16'135+136+ if len(head) == 4:137+ if head[:3] == b'\x00\x00\x00':138+ return 'utf-32-be'139+140+ if head[::2] == b'\x00\x00':141+ return 'utf-16-be'142+143+ if head[1:] == b'\x00\x00\x00':144+ return 'utf-32-le'145+146+ if head[1::2] == b'\x00\x00':147+ return 'utf-16-le'148+149+ if len(head) == 2:150+ return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'151+152+ return 'utf-8'153+154+155 def dumps(obj, **kwargs):156 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's157 configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an158 application on the stack.26 unmodified lines185 application on the stack.186 """187 _load_arg_defaults(kwargs)188 if isinstance(s, bytes):145- s = s.decode(kwargs.pop('encoding', None) or 'utf-8')189+ encoding = kwargs.pop('encoding', None)190+ if encoding is None:191+ encoding = detect_encoding(s)192+ s = s.decode(encoding)193 return _json.loads(s, **kwargs)194 195 196 def load(fp, **kwargs):120 unmodified linesmodified:flask/wrappers.py+3 added-10 removed
142 unmodified lines143 144 if not (force or self.is_json):145 return None146 147- # We accept a request charset against the specification as148- # certain clients have been using this in the past. This149- # fits our general approach of being nice in what we accept150- # and strict in what we send out.151- request_charset = self.mimetype_params.get('charset')147+ data = _get_data(self, cache)148+149 try:153- data = _get_data(self, cache)154- if request_charset is not None:155- rv = json.loads(data, encoding=request_charset)156- else:157- rv = json.loads(data)150+ rv = json.loads(data)151 except ValueError as e:152 if silent:153 rv = None154 else:44 unmodified linesmodified:tests/test_helpers.py+16 added-12 removed
19 unmodified lines20 from werkzeug.datastructures import Range21 from werkzeug.exceptions import BadRequest, NotFound22 from werkzeug.http import parse_cache_control_header, parse_options_header23 from werkzeug.http import http_date24+25+from flask import json26 from flask._compat import StringIO, text_type27 28 29 def has_encoding(name):5 unmodified lines35 return False36 37 38 class TestJSON(object):39+ @pytest.mark.parametrize('value', (40+ 1, 't', True, False, None,41+ [], [1, 2, 3],42+ {}, {'foo': u'🐍'},43+ ))44+ @pytest.mark.parametrize('encoding', (45+ 'utf-8', 'utf-8-sig',46+ 'utf-16-le', 'utf-16-be', 'utf-16',47+ 'utf-32-le', 'utf-32-be', 'utf-32',48+ ))49+ def test_detect_encoding(self, value, encoding):50+ data = json.dumps(value).encode(encoding)51+ assert json.detect_encoding(data) == encoding52+ assert json.loads(data) == value53 54 def test_ignore_cached_json(self):55 app = flask.Flask(__name__)56 with app.test_request_context('/', method='POST', data='malformed',43 unmodified lines100 c = app.test_client()101 rv = c.post('/json', data='"foo"', content_type='application/x+json')102 assert rv.data == b'foo'103 88- def test_json_body_encoding(self):89- app = flask.Flask(__name__)90- app.testing = True91- @app.route('/')92- def index():93- return flask.request.get_json()94-95- c = app.test_client()96- resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),97- content_type='application/json; charset=iso-8859-15')98- assert resp.data == u'Hällo Wörld'.encode('utf-8')99-104 def test_json_as_unicode(self):105 app = flask.Flask(__name__)106 107 app.config['JSON_AS_ASCII'] = True802 unmodified lines