python中的发布/订阅和rpc库
项目描述
pyspoke
在 Linux 上支持 pubsub 和远程过程调用的 python 库。
概述
这个包提供了一个 python 库,用于在进程之间传递 JSON 消息。客户端将消息发布到命名通道并订阅通道以接收这些消息。每个客户端都连接到充当消息代理的单个服务器。特点包括:
- 支持通配符订阅的分层频道名称
- 建立在发布/订阅功能之上的远程过程调用
- 由服务器记录并发送给稍后订阅频道的客户端的持久消息
- 桥接服务器,使它们和它们的客户端表现得像一个单一的网络
- 可定制的传输协议 - 默认是 TCP 套接字
- 使用标准 asyncio 模块的异步客户端/服务器代码
- 发布和 rpc 调用的同步包装函数
安装
需要 Python 3.7 或更高版本
来自PyPI
使用 pip 安装:
python3 -m pip install pyspoke
来自最新消息
首先安装构建依赖项:
python3 -m pip install build
构建分布:
git clone https://gitlab.com/samflam/pyspoke.git
cd pyspoke
make
要安装,您可以pip install内置轮子dist或简单地运行
make install
测试
从顶层开始,执行:
make test
例子
基本发布者和订阅者
首先,我们运行充当消息代理的服务器,接收发布的消息并将它们发送给订阅的客户端:
"Server code"
import asyncio
import spoke
server = spoke.pubsub.server.Server()
try:
asyncio.run(server.run())
except KeyboardInterrupt:
pass
接下来,我们需要一个订阅者来监听给定频道上的消息,并在收到消息时执行回调函数。在这种情况下,我们监听foo频道上的消息并将它们打印出来:
"Subscriber"
import asyncio
import spoke
async def handle_foo(msg):
print(f"Got message on foo channel: {msg.body}")
async def main():
client = spoke.pubsub.client.Client()
await client.run()
await client.subscribe("foo", handle_foo)
await spoke.wait()
asyncio.run(main())
foo最后我们在频道上发布一条消息。这个例子使用了同步包装函数,使用起来比较简单,但是每次调用都必须建立一个新的连接:
"Publisher (using simple synchronous call)"
import spoke
spoke.publish("foo", 5)
连接选项
默认情况下,客户端假定服务器位于localhost:7181; 服务器绑定到0.0.0.0:7181. 默认值可能会更改:
# server and client-subscriber are configured inside a map, the named argument conn_opts:
server = spoke.pubsub.server.Server(conn_opts = {"host": "localhost", "port": 4444, "reuse": True})
server = spoke.pubsub.server.Server(conn_opts = {"reuse": True})
client = spoke.pubsub.client.Client(conn_opts = {"host": "spoke", "port": 8888})
client = spoke.pubsub.client.Client(conn_opts = {"host": "spoke"})
# the publisher is different; it takes host and port themselves as named arguments:
spoke.publish('world', 'Hello!', host="spoke", port=8888)
spoke.publish('dazai', 'BSD', port=8888)
命令行界面
该软件包为常见任务提供了多个命令行脚本。如需对其中任何一个的帮助,请使用以下标志运行-h:
spoke-server- 运行充当消息代理的服务器spoke-echo- 订阅给定的频道并打印它收到的任何消息spoke-publish- 在给定频道上发布消息spoke-call- 在给定通道上进行远程过程调用并打印结果spoke-bridge- 连接两个辐条服务器,使它们和它们的客户端透明地表现得像一个单一的网络
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。
源分布
pyspoke-1.1.1.tar.gz
(11.5 kB
查看哈希)
内置分布
pyspoke-1.1.1-py3-none-any.whl
(15.8 kB
查看哈希)