[英]flask-marshmallow serialize datetime to unix timestamp?
Default, DateTime fields will be serialized to a format like 2020-02-02T13:25:33
, but I want to serialized it to unix timestamp.默认情况下, DateTime 字段将序列化为
2020-02-02T13:25:33
类的格式,但我想将其序列化为 unix 时间戳。 I've read flask-marshmallow documents and marshmallow documents, I only find ways to custom the output datetime format.我读过flask-marshmallow 文档和棉花糖文档,我只找到自定义输出日期时间格式的方法。 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')
The way you're doing it makes sense.你这样做的方式是有道理的。
You could money-patch DateTime
rather than overriding it to simplify the imports throughout your application.您可以修补
DateTime
而不是覆盖它以简化整个应用程序的导入。 Just modify fields.DateTime.SERIALIZATION_FUNCS
and fields.DateTime.DESERIALIZATION_FUNCS
and you're done.只需修改
fields.DateTime.SERIALIZATION_FUNCS
和fields.DateTime.DESERIALIZATION_FUNCS
就完成了。
Serialization to/from timestamp is an old TODO but we're not done with it yet:序列化到/从时间戳是一个旧的 TODO 但我们还没有完成它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.