8

Python 怎么实现类似 go 那种通过字段 tag 实现各种格式的序列化、反序列化、以及校验...

 2 years ago
source link: https://www.v2ex.com/t/919061
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

Python 怎么实现类似 go 那种通过字段 tag 实现各种格式的序列化、反序列化、以及校验等特征

  1800x · 3 小时 12 分钟前 · 502 次点击

比如下面的 Go 结构体:

type CompanyBase struct {
	// ID id
	ID int64 `json:"id" db:"id"`

	// Name 名称
	Name string `json:"name" db:"title"`

	// Deleted 逻辑删除标志。0 为未删除。1 为已删除
	Deleted bool `json:"deleted" db:"deleted"`

	// CreateTime 创建时间
	CreateTime time.Time `json:"create_time" db:"create_time"`

	// UpdateTime 更新时间
	UpdateTime time.Time `json:"update_time" db:"update_time"`
}

上面结构体字段 tag ,json 用于 json 序列化和反序列化,db 用于数据库序列化和反序列化。
还可以加别的标签,实现校验。这个例子没有。
当然,得有一个库,读取字段标签,执行序列化、反序列化、校验等功能。
另外,还得支持嵌套结构。

如果换了是 python ,怎么实现?


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK