Files
session_redis_public/session_redis/json_encoding.py
T
Guewen Baconnier 2a022ba537 Encode/decode date and datetime in redis sessions
In several places, odoo sets a datetime object directly in the
session. It works with the default session handler of odoo which
uses pickle.

But datetime and date are not json serializable by default.

Add custom encoder / decoder to handle them (from
https://github.com/OCA/queue/blob/dc12a6a20ecfd15c5b90f9b089c9a64cf9d8bbe4/queue_job/fields.py#L57-L99)

See the discussion raised by @PCatinean on https://github.com/camptocamp/odoo-cloud-platform/pull/176
2020-05-26 11:39:30 +02:00

40 lines
1.2 KiB
Python

# Copyright 2016-2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
import json
from datetime import date, datetime
import dateutil
class SessionEncoder(json.JSONEncoder):
"""Encode date/datetime objects
So that we can later recompose them if they were stored in the session
"""
def default(self, obj):
if isinstance(obj, datetime):
return {"_type": "datetime_isoformat", "value": obj.isoformat()}
elif isinstance(obj, date):
return {"_type": "date_isoformat", "value": obj.isoformat()}
return json.JSONEncoder.default(self, obj)
class SessionDecoder(json.JSONDecoder):
"""Decode json, recomposing recordsets and date/datetime"""
def __init__(self, *args, **kwargs):
super().__init__(object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
if "_type" not in obj:
return obj
type_ = obj["_type"]
if type_ == "datetime_isoformat":
return dateutil.parser.parse(obj["value"])
elif type_ == "date_isoformat":
return dateutil.parser.parse(obj["value"]).date()
return obj