默认情况下,DateTime 字段将被序列化为类似的格式2020-02-02T13:25:33
,但我想将其序列化为 unix 时间戳。我已经阅读了flask-marshmallow 文档和marshmallow文档,我只找到了自定义输出日期时间格式的方法。所以我的问题是,我可以采取任何简单的解决方案来实现这一目标吗?
我有一个模型定义:
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)
它的模式定义:
class FolderSchema(marshmallow.Schema):
create_time = DateTime(format='timestamp')
update_time = DateTime(format='timestamp')
我找到了一种非常复杂的方法来实现这一点,我正在尝试找到另一种简单的方法。
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')