Skip to content

Commit

Permalink
Make JSONEncoder keep the same type for date/datetime.
Browse files Browse the repository at this point in the history
Otherwise Celery jobs start to get `datetime` in place of `date` and that
could lead to errors.

See celery/celery#7754, related PR celery#1515.
  • Loading branch information
mvaled committed Sep 20, 2022
1 parent afcde0a commit 46fb502
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ Lorenzo Mancini <lmancini@develer.com>
Luyun Xie <2304310@qq.com>
Mads Jensen <https://github.com/atombrella>
Mahendra M <Mahendra_M@infosys.com>
Manuel Vazquez Acosta <https://github.com/mvaled>
Marcin Lulek (ergo) <info@webreactor.eu>
Marcin Puhacz <marcin.puhacz@gmail.com>
Mark Lavin <mlavin@caktusgroup.com>
Expand Down
7 changes: 6 additions & 1 deletion kombu/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,13 @@ def default(self, o,
return reducer()
else:
if isinstance(o, dates):
marker = "__date__"
if not isinstance(o, datetime):
o = datetime(o.year, o.month, o.day, 0, 0, 0, 0)
else:
marker = "__datetime__"
r = o.isoformat()
return {"datetime": r, "__datetime__": True}
return {"datetime": r, marker: True}
elif isinstance(o, times):
return o.isoformat()
elif isinstance(o, uuid.UUID):
Expand Down Expand Up @@ -71,6 +74,8 @@ def dumps(s, _dumps=json.dumps, cls=None, default_kwargs=None, **kwargs):

def object_hook(dct):
"""Hook function to perform custom deserialization."""
if "__date__" in dct:
return datetime.datetime.fromisoformat(dct["datetime"]).date()
if "__datetime__" in dct:
return datetime.datetime.fromisoformat(dct["datetime"])
if "__bytes__" in dct:
Expand Down
4 changes: 2 additions & 2 deletions t/unit/utils/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import uuid
from collections import namedtuple
from datetime import datetime
from datetime import date, datetime
from decimal import Decimal
from unittest.mock import MagicMock, Mock

Expand Down Expand Up @@ -39,7 +39,7 @@ def test_datetime(self):
'datetime': now,
'tz': now_utc,
'time': now.time().isoformat(),
'date': datetime(now.year, now.month, now.day, 0, 0, 0, 0),
'date': date(now.year, now.month, now.day),
}

@given(message=st.binary())
Expand Down

0 comments on commit 46fb502

Please sign in to comment.