跳转到主要内容

类型安全的自动序列化和反序列化JSON RPC客户端。最佳搭配instant_api。

项目描述

instant_client

Build Status Coverage Status Supports Python versions 3.7+

A type-safe JSON-RPC client with automatic (de)serialization.

pip install instant-client

对于通过HTTP(如下例所示)进行通信

pip install 'instant-client[requests]'

instant_client可用于与任何实现JSON-RPC的服务器通信,但最好与instant_api搭配使用。例如,假设API服务器配置如下

from dataclasses import dataclass
from flask import Flask
from instant_api import InstantAPI

app = Flask(__name__)

@dataclass
class Point:
    x: int
    y: int

@InstantAPI(app)
class Methods:
    def translate(self, p: Point, dx: int, dy: int) -> Point:
        return Point(p.x + dx, p.y + dy)

    def scale(self, p: Point, factor: int) -> Point:
        return Point(p.x * factor, p.y * factor)

if __name__ == '__main__':
    app.run()

然后使用客户端就像这样简单

from server import Methods, Point  # the classes we defined above
from instant_client import InstantClient

# The type hint is a lie, but your linter/IDE doesn't know that!
methods: Methods = InstantClient("http://127.0.0.1:5000/api/", Methods()).methods

assert methods.scale(Point(1, 2), factor=3) == Point(3, 6)

这看起来就像直接调用了Methods.scale(),这正是(没有故意)要点,但在底层它确实向服务器发送了一个HTTP请求!更手动编写的相同代码如下

import requests

response = requests.post(
    'http://127.0.0.1:5000/api/',
    json={
        'id': 0, 
        'jsonrpc': '2.0', 
        'method': 'scale', 
        'params': {
            'p': {'x': 1, 'y': 2}, 
            'factor': 3,
        },
    },
)

assert response.json()['result'] == {'x': 3, 'y': 6}

通常,InstantClient构造函数有两个必需参数

  1. 用于您所需传输的jsonrpcclient库的客户端。例如

    from jsonrpcclient.clients.zeromq_client import ZeroMQClient
    from instant_client import InstantClient
    
    client = InstantClient(ZeroMQClient("tcp://localhost:5000"), Methods())
    

    作为一个便利,你也可以传递一个表示URL的字符串,这将用于构建一个HTTPClient

  2. 一个定义您的方法的对象。方法体可以是空的,InstantClient仅使用签名和类型提示来序列化参数并使用datafunctions的帮助反序列化结果。

客户端的methods属性是一个简单的代理,所以这个

client.methods.scale(Point(1, 2), factor=3)

等同于

client.request("scale", Point(1, 2), factor=3)

然后查找原始方法的签名。

您的IDE/linter/类型检查器应认为client.methods是您最初传入的对象,因此您可以获得所有常规警告和自动完成。添加您自己的类型提示可能会有所帮助,但通常不是必需的。

项目详情


下载文件

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

源分发

本发布没有提供源分发文件。请参阅关于 生成分发存档 的教程。

构建分发

instant_client-0.0.1-py3-none-any.whl (5.7 kB 查看哈希值)

上传时间 Python 3

支持者