跳转到主要内容

eth-pydantic-types: 以太坊的Pydantic类型

项目描述

eth-pydantic-types

本包中的类型是受eth-typing启发的以太坊Pydantic类型。

哈希

HashBytes{n}HashStr{n} 是当您的十六进制值有大小限制时使用的好类型。这两种类型在JSON模式中都序列化为 string。当您希望类型在Pydantic核心模式中序列化为字节时,请使用 HashBytes 类型;当您希望类型在核心Pydantic模式中序列化为 str 时,请使用 HashStr 类型。

from pydantic import BaseModel

from eth_pydantic_types import HashBytes32, HashStr20

# When serializing to JSON, both types are hex strings.
class Transaction(BaseModel):
    tx_hash: HashBytes32  # Will be bytes
    address: HashStr20  # Will be str


# NOTE: I am able to pass an int-hash as the value and it will
#  get validated and type-coerced.
tx = Transaction(
    tx_hash=0x1031f0c9ac54dcb64b4f121a27957c14263c5cb49ed316d568e41e19c34d7b28,
    address=0x1031f0c9ac54dcb64b4f121a27957c14263c5cb4,
)

HexBytes

这是一个围绕已非常薄的包装器 hexbytes.HexBytes 的薄包装器。这里的区别在于这个HexBytes能够正确序列化。在任何您实际使用 hexbytes.HexBytes 的地方使用 HexBytes。 HexBytes 在Pydantic核心模式中序列化为字节,在JSON模式中以二进制格式序列化为 string

from pydantic import BaseModel
from eth_pydantic_types import HexBytes

class MyStorage(BaseModel):
    cid: HexBytes

# NOTE: We are able to pass a hex-str for a HexBytes value.
storage = MyStorage(cid="0x123")

Address

使用 Address 类来处理校验和地址。在模型构造过程中对地址进行验证和校验和。地址在Pydantic核心模式中序列化为 str,在JSON模式中以二进制格式序列化为 string

from pydantic import BaseModel
from eth_pydantic_types import Address

class Account(BaseModel):
    address: Address

# NOTE: The address ends up checksummed
#   ("0x0837207e343277CBd6c114a45EC0e9Ec56a1AD84")
account = Account(address="0x837207e343277cbd6c114a45ec0e9ec56a1ad84")

HexStr

使用十六进制字符串时,只需关注无大小的十六进制字符串。在Pydantic核心模式中,HexStr类型序列化为str,在JSON模式中序列化为二进制格式的string

from eth_pydantic_types import HexStr
from pydantic import BaseModel

class Tx(BaseModel):
    data: HexStr

tx = Tx(data="0x0123")

Bip122Uri

通过使用Bip122Uri类型来注解模型,以在模型中使用BIP-122 URIs。此类型在Pydantic核心模式中序列化为str,以及在JSON模式中序列化为string,但是会验证各个哈希值。

from eth_pydantic_types import Bip122Uri
from pydantic import BaseModel

class Message(BaseModel):
    path: Bip122Uri

message = Message(
    path=(
        "blockchain://d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"
        "/block/752820c0ad7abc1200f9ad42c4adc6fbb4bd44b5bed4667990e64565102c1ba6"
    )
)

项目详情


下载文件

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

源分布

eth-pydantic-types-0.1.3.tar.gz (65.7 kB 查看哈希值)

上传时间

构建分布

eth_pydantic_types-0.1.3-py3-none-any.whl (14.6 kB 查看哈希值)

上传时间 Python 3

支持者