diff --git a/CHANGES b/CHANGES index 0c36e6c422..6cad64b3cf 100644 --- a/CHANGES +++ b/CHANGES @@ -61,6 +61,7 @@ Version 1.0 - The automatically provided ``OPTIONS`` method is now correctly disabled if the user registered an overriding rule with the lowercase-version ``options`` (issue ``#1288``). +- flask.json.jsonify now supports the datetime.date type Version 0.10.2 -------------- diff --git a/flask/json.py b/flask/json.py index 32060061a2..d68189fc26 100644 --- a/flask/json.py +++ b/flask/json.py @@ -10,7 +10,7 @@ """ import io import uuid -from datetime import datetime +from datetime import date from .globals import current_app, request from ._compat import text_type, PY2 @@ -74,8 +74,8 @@ def default(self, o): return list(iterable) return JSONEncoder.default(self, o) """ - if isinstance(o, datetime): - return http_date(o) + if isinstance(o, date): + return http_date(o.timetuple()) if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 5fce5a45a0..7b5b32f203 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -12,9 +12,11 @@ import pytest import os +import datetime import flask from logging import StreamHandler from werkzeug.http import parse_cache_control_header, parse_options_header +from werkzeug.http import http_date from flask._compat import StringIO, text_type @@ -29,6 +31,24 @@ def has_encoding(name): class TestJSON(object): + def test_jsonify_date_types(self): + """Test jsonify with datetime.date and datetime.datetime types.""" + + test_dates = ( + datetime.datetime(1973, 3, 11, 6, 30, 45), + datetime.date(1975, 1, 5) + ) + + app = flask.Flask(__name__) + c = app.test_client() + + for i, d in enumerate(test_dates): + url = '/datetest{0}'.format(i) + app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) + rv = c.get(url) + assert rv.mimetype == 'application/json' + assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple()) + def test_json_bad_requests(self): app = flask.Flask(__name__) @app.route('/json', methods=['POST'])