定义可序列化类的库。

serialobj的Python项目详细描述


serialobject是一个支持从json到json的序列化的对象 对象(内置类型的指令和列表)。

序列化规范取自__fields__class属性, 在表格上:

__fields__: {
    FIELD_NAME: FIELD_SPEC
}

字段名是一个字符串,它唯一的约束是它应该是一个有效的 对象属性名称。

字段规格可以是:

  • 任何本机类型:

    • ^{tt2}$
    • ^{tt3}$ (Python2)
    • ^{tt4}$
    • ^{tt5}$
    • ^{tt6}$
    • ^{tt7}$
  • aSerialObject子类

  • Choice(val1, val2, ...)若要形成枚举,值应为a

    本机类型(见上文)。

  • [FIELD_SPEC]:由上述规范描述的对象列表。

此外,serialobjects还支持__strict__boolean类属性 (默认为False)。当__strict__==true时,将执行耗尽性检查。 在(反)序列化过程中,缺少或未知密钥会产生错误。

在python2上,str实例自动强制为unicode字符串。

安装

serialobj已在pypi上注册。只需键入以下命令。

pip install serialobj

或者,在克隆了 源存储库:

python setup.py install

快速教程

简单类型和继承

让我们定义一个非常基本的person类型,它定义了两个字符串字段:

class Person(SerialObject):
    __fields__ = {
        'name': str,
        'job': str
    }

现在我们可以简单地将json兼容的数据反序列化到它,和/或序列化它 类json结构的实例:

>>> person_data = {
...     'name': 'Bob',
...     'job': 'lumberjack'
... }
>>> bob = Person.deserialize(person_data)
>>> bob.name
'Bob'
>>> bob.job
'lumberjack'
>>> bob.serialize()
{'job': 'lumberjack', 'name': 'Bob'}

当然还有比这更重要的。让我们将Person子类化为 例如,定义一个TeamMate,它重写job字段以允许它 成为dict并添加新的str字段:role

class TeamMate(Person):
    __fields__ = {
        'role': str,
        'job': dict
    }

当然这是一个愚蠢的例子,但这让我们可以证明 继承serialobject类允许继承、重写和专门化 结构定义:

>>> bob2 = TeamMate.deserialize(teammate_data)
>>> bob2.name
'Bob'
>>> bob2.job
{'all night': 'sleep', 'all day': 'work'}
>>> bob2.serialize()
{'role': 'lumberjack', 'name': 'Bob', 'job': {'all night': 'sleep', 'all day': 'work'}}

它还允许我们演示结构实际上是checked 针对模型:让我们尝试使用 不兼容的Person模型。

>>> Person.deserialize(teammate_data)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Person.deserialize(teammate_data)
  File "/home/arnaud/work/serialobj/serialobj.py", line 242, in deserialize
    for key, val in data.items() if key in cls.__fields__
  File "/home/arnaud/work/serialobj/serialobj.py", line 242, in <dictcomp>
    for key, val in data.items() if key in cls.__fields__
  File "/home/arnaud/work/serialobj/serialobj.py", line 86, in deserialize
    .format(self.cls_.__name__, data))
serialobj.InvalidTypeError: Expected str, got {'all night': 'sleep', 'all day': 'work'}

是不是开始变得有趣了?

对象列表

让我们再加点香料。如果我想将字段定义为 字符串?

嗯,这里有一些糖:

class Task(SerialObject):
    __fields__ = {
        'title': str,
        'description': str,
        'checklist': [str]
    }

自己看看:

>>> data = {
...     'title': 'timber some wood',
...     'description': '',
...     'checklist': [
...         'some wood is timbered',
...         'the lumberjack is okay',
...         'he sleeps all night and works all day'
...     ]
... }
>>> tsk = Task.deserialize(data)
>>> tsk.checklist
['some wood is timbered', 'the lumberjack is okay', 'he sleeps all night and works all day']
>>> tsk.checklist.append("... and that's it")
>>> pprint(tsk.serialize())
{'checklist': ['some wood is timbered',
               'the lumberjack is okay',
               'he sleeps all night and works all day',
               "... and that's it"],
 'description': '',
 'title': 'timber some wood'}

喜欢

当然,所有这些都是可以任意定义的基本构造块 复杂的JSON-API结构:

class Team(SerialObject):
    __fields__ = {
        'name': str,
        'manager': TeamMate,
        'members': [TeamMate],
        'backlog': [Task]
    }


COMPLEX_DATA = {
    'name': "The good ol' lumberjacks",
    'manager': {
        'name': 'Bob',
        'role': 'Be okay'
    },
    'members': [
        {
            'name': 'Jack',
            'role': 'sleep all night'
        },
        {
            'name': 'Barry',
            'role': 'work all day',
        }],
    'backlog': [
        {
            'title': 'timber some wood',
            'description': '',
            'checklist': [
                'some wood is timbered',
                'the lumberjack is okay',
                'he sleeps all night and works all day'
            ]
        }]
    }

我们开始了:

>>> team = Team.deserialize(COMPLEX_DATA)
>>> team.manager.name
'Bob'
>>> team.manager
<__console__.TeamMate object at 0x7f34edd2c9a8>
>>> team.backlog[0]
<__console__.Task object at 0x7f34edd9b7c8>
>>> team.backlog[0].title
'timber some wood'
>>> pprint(team.serialize())
{'backlog': [{'checklist': ['some wood is timbered',
                            'the lumberjack is okay',
                            'he sleeps all night and works all day'],
              'description': '',
              'title': 'timber some wood'}],
 'manager': {'name': 'Bob', 'role': 'Be okay'},
 'members': [{'name': 'Jack', 'role': 'sleep all night'},
             {'name': 'Barry', 'role': 'work all day'}],
 'name': "The good ol' lumberjacks"}

测试

您可以使用tox触发所有测试。当前正在为python运行测试 2.7和3.5。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Maven无法识别安装在Ubuntu外壳上的$java_HOME jdk   java如何防止可运行程序在其中一个抛出异常时执行   java Listview在按下项时不触发   如何在WindowsPhone8中使用JavaRESTWebService?   java在spring引导下使用多个dispatcher servlet/web上下文   java为什么在删除容器的绝对大小时不绘制GEF子项?   java在hibernate实体中保留DB约束是好的   JavaSpring选择最高优先级bean   ArrayList<Class>java字符串[]   有向加权边图的Java邻接表实现   字母数字字符串的java Tesseract配置:混合2、Z、6和G   如果输入为空,则带有EditText的java警报对话框将关闭   jsp上的java Struts 2动作响应   java获取IndexOutOfBundException Android   scala AWSJAVASDK:解压缩大小必须小于262144000字节