Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add datetime.date support to JSONEncoder #1326

Merged
merged 1 commit into from
Jan 23, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------
Expand Down
6 changes: 3 additions & 3 deletions flask/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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__'):
Expand Down
20 changes: 20 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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'])
Expand Down