Default, DateTime fields will be serialized to a format like 2020-02-02T13:25:33
, but I want to serialized it to unix timestamp. I've read flask-marshmallow documents and marshmallow documents, I only find ways to custom the output datetime format. So my question is that any simple solution can I do to achieve that?
I have a model definition:
class Folder(CRUDMixin, db.Model):
__tablename__ = 'folder'
create_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
update_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
And it's schema definition:
class FolderSchema(marshmallow.Schema):
create_time = DateTime(format='timestamp')
update_time = DateTime(format='timestamp')
I have found a quite complex way to achieve that, I'm trying to find another simple way.
class DateTime(fields.DateTime):
"""
Class extends marshmallow standard DateTime with "timestamp" format.
"""
SERIALIZATION_FUNCS = \
fields.DateTime.SERIALIZATION_FUNCS.copy()
DESERIALIZATION_FUNCS = \
fields.DateTime.DESERIALIZATION_FUNCS.copy()
SERIALIZATION_FUNCS['timestamp'] = lambda x: int(x.timestamp()) * 1000
DESERIALIZATION_FUNCS['timestamp'] = datetime.fromtimestamp
class FolderSchema(marshmallow.Schema):
create_time = DateTime(format='timestamp')
update_time = DateTime(format='timestamp')