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 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

4 files+82 added−26 removed

modified:flask/json/__init__.py+48 added-2 removed
4 unmodified lines
56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""99import codecs10import io11import uuid12from datetime import date, datetime13from flask.globals import current_app, request
106 unmodified lines
120 else:121 kwargs.setdefault('cls', JSONDecoder)122123124def detect_encoding(data):125 """Detect which UTF codec was used to encode the given bytes.126127 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.130131 :param data: Bytes in unknown UTF encoding.132 :return: UTF encoding name133 """134 head = data[:4]135136 if head[:3] == codecs.BOM_UTF8:137 return 'utf-8-sig'138139 if b'\x00' not in head:140 return 'utf-8'141142 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):143 return 'utf-32'144145 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):146 return 'utf-16'147148 if len(head) == 4:149 if head[:3] == b'\x00\x00\x00':150 return 'utf-32-be'151152 if head[::2] == b'\x00\x00':153 return 'utf-16-be'154155 if head[1:] == b'\x00\x00\x00':156 return 'utf-32-le'157158 if head[1::2] == b'\x00\x00':159 return 'utf-16-le'160161 if len(head) == 2:162 return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'163164 return 'utf-8'165166167def 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 lines
197 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)206207208def load(fp, **kwargs):
119 unmodified lines
modified:flask/wrappers.py+11 added-13 removed
48 unmodified lines
49 def _get_data_for_json(self, cache):50 return self.get_data(cache=cache)5152 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.5859 :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]6768 if not (force or self.is_json):69 return None7069 # 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)7273 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 lines
modified:tests/test_helpers.py+19 added-11 removed
14 unmodified lines
1516import pytest17from werkzeug.datastructures import Range18from werkzeug.exceptions import BadRequest, NotFound19from werkzeug.http import http_date, parse_cache_control_header, \19from werkzeug.http import (20 http_date, parse_cache_control_header,21 parse_options_header22)2324import flask25from flask import json26from flask._compat import StringIO, text_type27from flask.helpers import get_debug_flag, get_env2829
27 unmodified lines
57 return datetime.timedelta()585960class 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) == value7576 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 None
58 unmodified lines
138139 rv = client.post('/json', data='"foo"', content_type='application/x+json')140 assert rv.data == b'foo'141124 def test_json_body_encoding(self, app, client):125126 @app.route('/')127 def index():128 return flask.request.get_json()129130 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')133142 @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])143 def test_json_as_unicode(self, test_value, expected, app, app_ctx):144145 app.config['JSON_AS_ASCII'] = test_value
802 unmodified lines
modified:CHANGES.rst+4 added
145 unmodified lines
146- 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`_)153154.. _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/1489
37 unmodified lines
194.. _#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/2691199200201Version 0.12.2202--------------
618 unmodified lines