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
Provenance
- Commit
d625d41- Tree
5b36a1c- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1e112cc- Parent 2
63ccdad
3 files changed+35 added−1 removed
modified:flask/json/__init__.py+3 added-1 removed
1 # -*- coding: utf-8 -*-2 import io3 import uuid4-from datetime import date4+from datetime import date, datetime5 from flask.globals import current_app, request6 from flask._compat import text_type, PY27 8 from werkzeug.http import http_date52 unmodified lines61 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 linesmodified:tests/test_helpers.py+30 added
32 unmodified lines33 except LookupError:34 return False35 36 37+class FixedOffset(datetime.tzinfo):38+ """Fixed offset in hours east from UTC.39+40+ This is a slight adaptation of the ``FixedOffset`` example found in41+ https://docs.python.org/2.7/library/datetime.html.42+ """43+44+ def __init__(self, hours, name):45+ self.__offset = datetime.timedelta(hours=hours)46+ self.__name = name47+48+ def utcoffset(self, dt):49+ return self.__offset50+51+ def tzname(self, dt):52+ return self.__name53+54+ def dst(self, dt):55+ return datetime.timedelta()56+57+58 class 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 lines197 rv = client.get(url)198 assert rv.mimetype == 'application/json'199 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())200 201+ @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) == expected209+210 def test_jsonify_uuid_types(self, app, client):211 """Test jsonify with uuid.UUID types"""212 213 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)763 unmodified linesmodified:CHANGES+2 added
77 unmodified lines78 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`_)85 86 .. _#1489: https://github.com/pallets/flask/pull/148917 unmodified lines104 .. _#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/2373110 111 Version 0.12.2112 --------------618 unmodified lines