跳转到主要内容

一个库,用于将任何Python类型转换为易于序列化的类型

项目描述

preconvert - Supercharge Your Serializers

PyPI version Build Status codecov Gitter License Downloads


阅读最新文档 - 浏览GitHub代码仓库


Preconvert是一个库,它扩展了现有的序列化器(json、simplejson、bson、msgpack等),使其能够转换你使用的所有类型。它通过有效地预转换序列化器不熟悉的类型(如dataclasses和namedtuples)到所有序列化器都能理解的基本内置类型来实现这一点。然后,它提供一个机制,让你可以构建自定义预转换器,以及预转换插件,这些插件在通过pip安装时自动生效。

快速入门

  1. 使用pip安装preconvert

     pip3 install preconvert
    
  2. 用preconvert等效替换现有的json(或其他序列化库)

     from preconvert.output import simplejson as json
    
     ...
    
     json.dumps(MY_COMPLEX_OBJECT_WITH_DATA_CLASSSES)
    
  3. 为任何自定义类型定义预转换器,即使它们不在你的控制之下

     import numpy
     from preconvert import json
    
    
     class Employee:
    
         def __init__(self, first_name, last_name):
             self.first_name = first_name
             self.last_name = last_name
    
         def __preconvert__(self):
             return {'name': {'first': self.first_name, 'last': self.last_name}}
    
    
     @preconvert.converter(numpy.integer)
     def numpy_integer_to_python_int(numpy_int):
         return int(numpy_int)
    
    
     json.dumps({
         'employee': Employee('Timothy', 'Crosley'),
         'height_inches': numpy.int_(73)
     })
    
  4. 享受更全面和可配置的序列化器!

为什么?

你是否曾经尝试过对数据结构进行json.dumps操作,但惊讶地发现你的DataClass抛出了异常,或者你的namedtuple输出为一个列表?Preconvert就是为了解决跨常见序列化格式的问题而创建的。

在preconvert之前

import sys
import json
from dataclasses import dataclass


@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand


my_store_inventory = [InventoryItem("beer", unit_price=0.0, quantity_on_hand=sys.maxsize),  InventoryItem("bacon", unit_price=2.5, quantity_on_hand=3)]
json.dumps(my_store_inventory)

output >>>

    177
    178
--> 179         raise TypeError(f'Object of type {o.__class__.__name__} '
    180                         f'is not JSON serializable')
    181

TypeError: Object of type InventoryItem is not JSON serializable

D:

在preconvert之后

import sys
import json
from preconvert.output import json


@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand


my_store_inventory = [
    InventoryItem("beer", unit_price=0.0, quantity_on_hand=sys.maxsize),
    InventoryItem("bacon", unit_price=2.5, quantity_on_hand=3)
]
json.dumps(my_store_inventory)

>>> [
        {
            "name": "beer",
            "unit_price": 0.0,
            "quantity_on_hand": 9223372036854775807
        },
        {
            "name": "bacon",
            "unit_price": 2.5,
            "quantity_on_hand": 3
        }
    ]

:D

设计目标

  • 易于从现有项目中使用
  • 能够独立于期望的输出格式将复杂类型转换为简单类型
  • 为不受普遍支持的常见类型提供内置转换(dataclasses、namedtuple等...)
  • 提供构建自定义预转换器或覆盖内置预转换器的方法
  • 能够构建依赖于目标格式的预转换器
  • 与常用序列化格式结合使用时,开销最小

我该如何使用它?

如果你的项目使用我们内置支持的序列化器(json、msgpak、bson),你可以简单地替换现有的序列化器导入为预转换版本

from preconvert.outputs import json

或者

from preconvert.outputs import simplejson as json

或者

from preconvert.outputs import msgpack

或者

from preconvert.outputs import bson

如果不支持,你可以在使用其他序列化器之前注入preconvert,通常通过设置defaulton_onknown参数

import preconvert
import my_serializer

my_serializer.dumps(default=preconvert.default_serializable)

我该如何扩展它?

想要将预转换添加到自己的自定义类型?对于面向对象的项目,一个简单的方法是为你的对象添加一个__preconvert__方法

class MyCustomClass(object):
    def __init__(self, first_name, children=()):
        self.first_name = first_name
        self.children = children

    def __jsonifiable__(self)
        return {'first': self.first_name, 'children': children}

对于其他实体,如你无法控制的对象,你可以使用preconvert.converter装饰器注册一个新的预转换

import preconvert


@preconvert.converter(SomeFrameworkObject)
def convert_framework_object(instance):
    return {'name': instance.name}

你也可以可选地指定针对特定序列化格式的预转换

import preconvert


@preconvert.json(SomeFrameworkObject)
def convert_framework_object(instance):
    return {'json': {'name': instance.name}}


@preconvert.msgpack(SomeFrameworkObject)
def convert_framework_object(instance):
    return ['name', instance.name]

最后,你可以将包含转换器的任何模块注册为'preconvert.converters'入口点,只要包含它们的包已安装,它们就会自动生效。请参阅preconvert_numpy以了解其工作原理的示例。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

preconvert-0.0.6.tar.gz (128.5 kB 查看哈希值)

上传时间

构建分发

preconvert-0.0.6-py3-none-any.whl (17.3 kB 查看哈希值)

上传时间 Python 3

支持者:

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页