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 0cbe698 · Browse files · 4 files·+82 added−26 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+82 added−26 removed
- tests:+19 added−11 removed
- other:+63 added−15 removed
Provenance
- Commit
ab41422- Tree
b7608a6- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
0cbe698
4 files changed+82 added−26 removed
modified:flask/json/__init__.py+48 added-2 removed
4 unmodified lines5 6 :copyright: © 2010 by the Pallets team.7 :license: BSD, see LICENSE for more details.8 """9-9+import codecs10 import io11 import uuid12 from datetime import date, datetime13 from flask.globals import current_app, request106 unmodified lines120 else:121 kwargs.setdefault('cls', JSONDecoder)122 123 124+def detect_encoding(data):125+ """Detect which UTF codec was used to encode the given bytes.126+127+ The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is128+ accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big129+ or little endian. Some editors or libraries may prepend a BOM.130+131+ :param data: Bytes in unknown UTF encoding.132+ :return: UTF encoding name133+ """134+ head = data[:4]135+136+ if head[:3] == codecs.BOM_UTF8:137+ return 'utf-8-sig'138+139+ if b'\x00' not in head:140+ return 'utf-8'141+142+ if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):143+ return 'utf-32'144+145+ if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):146+ return 'utf-16'147+148+ if len(head) == 4:149+ if head[:3] == b'\x00\x00\x00':150+ return 'utf-32-be'151+152+ if head[::2] == b'\x00\x00':153+ return 'utf-16-be'154+155+ if head[1:] == b'\x00\x00\x00':156+ return 'utf-32-le'157+158+ if head[1::2] == b'\x00\x00':159+ return 'utf-16-le'160+161+ if len(head) == 2:162+ return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'163+164+ return 'utf-8'165+166+167 def dumps(obj, **kwargs):168 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's169 configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an170 application on the stack.26 unmodified lines197 application on the stack.198 """199 _load_arg_defaults(kwargs)200 if isinstance(s, bytes):158- s = s.decode(kwargs.pop('encoding', None) or 'utf-8')201+ encoding = kwargs.pop('encoding', None)202+ if encoding is None:203+ encoding = detect_encoding(s)204+ s = s.decode(encoding)205 return _json.loads(s, **kwargs)206 207 208 def load(fp, **kwargs):119 unmodified linesmodified:flask/wrappers.py+11 added-13 removed
48 unmodified lines49 def _get_data_for_json(self, cache):50 return self.get_data(cache=cache)51 52 def get_json(self, force=False, silent=False, cache=True):53- """Parse and return the data as JSON. If the mimetype does not indicate54- JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns55- ``None`` unless ``force`` is true. If parsing fails,56- :meth:`on_json_loading_failed` is called and its return value is used57- as the return value.53+ """Parse and return the data as JSON. If the mimetype does not54+ indicate JSON (:mimetype:`application/json`, see55+ :meth:`is_json`), this returns ``None`` unless ``force`` is56+ true. If parsing fails, :meth:`on_json_loading_failed` is called57+ and its return value is used as the return value.58 59 :param force: Ignore the mimetype and always try to parse JSON.60- :param silent: Silence parsing errors and return ``None`` instead.61- :param cache: Store the parsed JSON to return for subsequent calls.60+ :param silent: Silence parsing errors and return ``None``61+ instead.62+ :param cache: Store the parsed JSON to return for subsequent63+ calls.64 """65 if cache and self._cached_json[silent] is not Ellipsis:66 return self._cached_json[silent]67 68 if not (force or self.is_json):69 return None70 69- # We accept MIME charset against the specification as certain clients70- # have used this in the past. For responses, we assume that if the71- # charset is set then the data has been encoded correctly as well.72- charset = self.mimetype_params.get('charset')71+ data = self._get_data_for_json(cache=cache)72 73 try:75- data = self._get_data_for_json(cache=cache)76- rv = json.loads(data, encoding=charset)74+ rv = json.loads(data)75 except ValueError as e:76 if silent:77 rv = None78 if cache:121 unmodified linesmodified:tests/test_helpers.py+19 added-11 removed
14 unmodified lines15 16 import pytest17 from werkzeug.datastructures import Range18 from werkzeug.exceptions import BadRequest, NotFound19-from werkzeug.http import http_date, parse_cache_control_header, \19+from werkzeug.http import (20+ http_date, parse_cache_control_header,21 parse_options_header22+)23 24 import flask25+from flask import json26 from flask._compat import StringIO, text_type27 from flask.helpers import get_debug_flag, get_env28 29 27 unmodified lines57 return datetime.timedelta()58 59 60 class TestJSON(object):61+ @pytest.mark.parametrize('value', (62+ 1, 't', True, False, None,63+ [], [1, 2, 3],64+ {}, {'foo': u'🐍'},65+ ))66+ @pytest.mark.parametrize('encoding', (67+ 'utf-8', 'utf-8-sig',68+ 'utf-16-le', 'utf-16-be', 'utf-16',69+ 'utf-32-le', 'utf-32-be', 'utf-32',70+ ))71+ def test_detect_encoding(self, value, encoding):72+ data = json.dumps(value).encode(encoding)73+ assert json.detect_encoding(data) == encoding74+ assert json.loads(data) == value75+76 def test_ignore_cached_json(self, app):77 with app.test_request_context('/', method='POST', data='malformed',78 content_type='application/json'):79 assert flask.request.get_json(silent=True, cache=True) is None58 unmodified lines138 139 rv = client.post('/json', data='"foo"', content_type='application/x+json')140 assert rv.data == b'foo'141 124- def test_json_body_encoding(self, app, client):125-126- @app.route('/')127- def index():128- return flask.request.get_json()129-130- resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),131- content_type='application/json; charset=iso-8859-15')132- assert resp.data == u'Hällo Wörld'.encode('utf-8')133-142 @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])143 def test_json_as_unicode(self, test_value, expected, app, app_ctx):144 145 app.config['JSON_AS_ASCII'] = test_value802 unmodified linesmodified:CHANGES.rst+4 added
145 unmodified lines146 - A single trailing slash is stripped from the blueprint ``url_prefix``147 when it is registered with the app. (`#2629`_)148 - :meth:`Request.get_json() <flask.Request.get_json>` doesn't cache the149 result if parsing fails when ``silent`` is true. (`#2651`_)150+- :func:`request.get_json <flask.Request.get_json>` no longer accepts151+ arbitrary encodings. Incoming JSON should be encoded using UTF-8 per152+ :rfc:`8259`, but Flask will autodetect UTF-8, -16, or -32. (`#2691`_)153 154 .. _pallets/meta#24: https://github.com/pallets/meta/issues/24155 .. _#1421: https://github.com/pallets/flask/issues/1421156 .. _#1489: https://github.com/pallets/flask/pull/148937 unmodified lines194 .. _#2636: https://github.com/pallets/flask/pull/2636195 .. _#2635: https://github.com/pallets/flask/pull/2635196 .. _#2629: https://github.com/pallets/flask/pull/2629197 .. _#2651: https://github.com/pallets/flask/issues/2651198+.. _#2691: https://github.com/pallets/flask/pull/2691199 200 201 Version 0.12.2202 --------------618 unmodified lines