Skip to content
Myr

detect UTF encodings when loading json

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

authored by David Lord · committed by David Lord · parent aab4c8c · 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

3 files+67 added−23 removed

modified:flask/json.py+48 added-1 removed
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import codecs12import io13import uuid14from datetime import date15from .globals import current_app, request
92 unmodified lines
108 else:109 kwargs.setdefault('cls', JSONDecoder)110111112def detect_encoding(data):113 """Detect which UTF codec was used to encode the given bytes.114115 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.118119 :param data: Bytes in unknown UTF encoding.120 :return: UTF encoding name121 """122 head = data[:4]123124 if head[:3] == codecs.BOM_UTF8:125 return 'utf-8-sig'126127 if b'\x00' not in head:128 return 'utf-8'129130 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):131 return 'utf-32'132133 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):134 return 'utf-16'135136 if len(head) == 4:137 if head[:3] == b'\x00\x00\x00':138 return 'utf-32-be'139140 if head[::2] == b'\x00\x00':141 return 'utf-16-be'142143 if head[1:] == b'\x00\x00\x00':144 return 'utf-32-le'145146 if head[1::2] == b'\x00\x00':147 return 'utf-16-le'148149 if len(head) == 2:150 return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'151152 return 'utf-8'153154155def 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 lines
185 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)194195196def load(fp, **kwargs):
120 unmodified lines
modified:flask/wrappers.py+3 added-10 removed
142 unmodified lines
143144 if not (force or self.is_json):145 return None146147 # 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)148149 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 lines
modified:tests/test_helpers.py+16 added-12 removed
19 unmodified lines
20from werkzeug.datastructures import Range21from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_date2425from flask import json26from flask._compat import StringIO, text_type272829def has_encoding(name):
5 unmodified lines
35 return False363738class 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) == value5354 def test_ignore_cached_json(self):55 app = flask.Flask(__name__)56 with app.test_request_context('/', method='POST', data='malformed',
43 unmodified lines
100 c = app.test_client()101 rv = c.post('/json', data='"foo"', content_type='application/x+json')102 assert rv.data == b'foo'10388 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()9495 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')99104 def test_json_as_unicode(self):105 app = flask.Flask(__name__)106107 app.config['JSON_AS_ASCII'] = True
802 unmodified lines