Skip to content
Myr

Merge pull request #2374 from astralblue/json_encode_non_utc_datetimes

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

Correctly JSON-encode datetimes aware of non-UTC timezones

authored by David Lord · committed by GitHub · parents 1e112cc, 63ccdad · Browse files · 3 files+35 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+35 added−1 removed

  • tests:+30 added−0 removed
  • other:+5 added−1 removed

3 files+35 added−1 removed

modified:flask/json/__init__.py+3 added-1 removed
1# -*- coding: utf-8 -*-2import io3import uuid4from datetime import date4from datetime import date, datetime5from flask.globals import current_app, request6from flask._compat import text_type, PY278from werkzeug.http import http_date
52 unmodified lines
61 else:62 return list(iterable)63 return JSONEncoder.default(self, o)64 """65 if isinstance(o, datetime):66 return http_date(o.utctimetuple())67 if isinstance(o, date):68 return http_date(o.timetuple())69 if isinstance(o, uuid.UUID):70 return str(o)
203 unmodified lines
modified:tests/test_helpers.py+30 added
32 unmodified lines
33 except LookupError:34 return False353637class FixedOffset(datetime.tzinfo):38 """Fixed offset in hours east from UTC.3940 This is a slight adaptation of the ``FixedOffset`` example found in41 https://docs.python.org/2.7/library/datetime.html.42 """4344 def __init__(self, hours, name):45 self.__offset = datetime.timedelta(hours=hours)46 self.__name = name4748 def utcoffset(self, dt):49 return self.__offset5051 def tzname(self, dt):52 return self.__name5354 def dst(self, dt):55 return datetime.timedelta()565758class TestJSON(object):59 def test_ignore_cached_json(self, app):60 with app.test_request_context('/', method='POST', data='malformed',61 content_type='application/json'):
135 unmodified lines
197 rv = client.get(url)198 assert rv.mimetype == 'application/json'199 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())200201 @pytest.mark.parametrize('tz', (('UTC', 0), ('PST', -8), ('KST', 9)))202 def test_jsonify_aware_datetimes(self, tz):203 """Test if aware datetime.datetime objects are converted into GMT."""204 tzinfo = FixedOffset(hours=tz[1], name=tz[0])205 dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)206 gmt = FixedOffset(hours=0, name='GMT')207 expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')208 assert flask.json.JSONEncoder().encode(dt) == expected209210 def test_jsonify_uuid_types(self, app, client):211 """Test jsonify with uuid.UUID types"""212213 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)
763 unmodified lines
modified:CHANGES+2 added
77 unmodified lines
78 the response to make testing JSON response much easier. (`#2358`_)79- Removed error handler caching because it caused unexpected results for some80 exception inheritance hierarchies. Register handlers explicitly for each81 exception if you don't want to traverse the MRO. (`#2362`_)82- Fix incorrect JSON encoding of aware, non-UTC datetimes. (`#2374`_)83- Template auto reloading will honor the ``run`` command's ``debug`` flag even84 if ``app.jinja_env`` was already accessed. (`#2373`_)8586.. _#1489: https://github.com/pallets/flask/pull/1489
17 unmodified lines
104.. _#2352: https://github.com/pallets/flask/pull/2352105.. _#2354: https://github.com/pallets/flask/pull/2354106.. _#2358: https://github.com/pallets/flask/pull/2358107.. _#2362: https://github.com/pallets/flask/pull/2362108.. _#2374: https://github.com/pallets/flask/pull/2374109.. _#2373: https://github.com/pallets/flask/pull/2373110111Version 0.12.2112--------------
618 unmodified lines