serialize a object | 简易对象序列化工具
Project description
easyserializer
简易对象序列化工具 serialize a object
$ pip install easyserializer
from easyserializer import SerializeableObject, obj_to_dict, obj_to_json, serialize
import datetime
class Student(object):
role = 'student'
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
@property
def age(self):
return int(((datetime.datetime.now().date() - self.birthday).days) / 365)
class Teacher(SerializeableObject):
role = 'teacher'
def __init__(self, name, subject, students):
self.name = name
self.subject = subject
self.students = students
s0 = Student('Dad', datetime.date(1963, 7, 28))
s1 = Student('Mom', datetime.date(1964, 11, 2))
t = Teacher('Tao', 'physics', [s0, s1])
# =============== 传参说明 =================
# filter_fields: 指定输出字段,可使用 list 和 dict 两种传参形式
# 示例: obj_to_dict(obj, 'field1', 'field2', filter_fields=['field3', 'field4'])
# 默认为输出所有字段
# exclude_fields: 过滤不要输出字段
# limit_deep: 限制递归深度, 默认5层. 设为0则不限制递归深度(不建议这么做!)
# prune: 精简模式(只取 `__dict__` 中的字段, 默认不开启)
# 继承自 SerializeableObject 的对象直接调用 serialize 方法,该对象转换为 dict 返回
print(t.serialize())
print(t.serialize('name', 'students'))
# 调用对象的 to_json 方法,对象以 json 字符串形式返回 (可传入 json.dump 的参数如 `indent`)
print(t.to_json())
print(t.to_json(exclude_fields=['role'], indent=4))
# 也可以直接使用 obj_to_dict, obj_to_json 这些函数
print(obj_to_dict(t, limit_deep=2))
print(obj_to_json(t, prune=True, indent=4))
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
easyserializer-0.2.15.tar.gz
(3.8 kB
view details)
File details
Details for the file easyserializer-0.2.15.tar.gz
.
File metadata
- Download URL: easyserializer-0.2.15.tar.gz
- Upload date:
- Size: 3.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 876b02a93558ebb0be4c0e8521b5ecb683fb81e77992729ef2ff9eecb055af23 |
|
MD5 | eb36b5d5bd6282552507bf7a26571f42 |
|
BLAKE2b-256 | b9d1349b873578da3152f0161e5735fe50f0d714728f851f51c3ab59e9ffff68 |