一个小型的、模块化的、与传输和协议无关的rpc库,除其他外,它支持json-rpc和zmq。
tinyrpc的Python项目详细描述
注
Tinyrpc已经过修订。
当前版本只支持python3。 如果需要python2支持,请查看0.9.x版本。 当python2退役时,python2的支持将完全消失, 2020年的某个时候。
动机
截至本文撰写之时(2013年1月),已经有几个jsonrpc库出来了 在PyPI上,大多数人处理一个特定的用例(例如json via 使用twisted或tcp套接字的wsgi)。
但是,没有一个库可以方便地重用jsonrpc解析位 并替换不同的传输(即从json经由TCP到 使用WebSockets或0mq实现。
最后,所有这些库都有自己的调度接口和 处理jsonrpc的自定义实现。今天(2019年3月)的情况没有改变。
tinyrpc旨在通过将问题划分为干净的 可互换部件,便于添加新的传输方法,rpc 协议或调度员。
示例:
要创建接收和处理jsonrpc请求的服务器进程,请执行以下操作:
importgeventimportgevent.pywsgiimportgevent.queuefromtinyrpc.protocols.jsonrpcimportJSONRPCProtocolfromtinyrpc.transports.wsgiimportWsgiServerTransportfromtinyrpc.server.geventimportRPCServerGreenletsfromtinyrpc.dispatchimportRPCDispatcherdispatcher=RPCDispatcher()transport=WsgiServerTransport(queue_class=gevent.queue.Queue)# start wsgi server as a background-greenletwsgi_server=gevent.pywsgi.WSGIServer(('127.0.0.1',5000),transport.handle)gevent.spawn(wsgi_server.serve_forever)rpc_server=RPCServerGreenlets(transport,JSONRPCProtocol(),dispatcher)@dispatcher.publicdefreverse_string(s):returns[::-1]# in the main greenlet, run our rpc_serverrpc_server.serve_forever()
相应的客户端代码如下:
fromtinyrpc.protocols.jsonrpcimportJSONRPCProtocolfromtinyrpc.transports.httpimportHttpPostClientTransportfromtinyrpcimportRPCClientrpc_client=RPCClient(JSONRPCProtocol(),HttpPostClientTransport('http://127.0.0.1:5000/'))remote_server=rpc_client.get_proxy()# call a method called 'reverse_string' with a single string argumentresult=remote_server.reverse_string('Hello, World!')print("Server answered:",result)
文档
您很快就会发现tinyrpc比core有更多的文档和测试 代码,因此得名。参见文档 <;https://tinyrpc.readthedocs.org>;了解更多详细信息,特别是 结构部分以获得鸟瞰图。
安装
pip install tinyrpc
将安装具有默认依赖项的tinyrpc。
可选依赖项
根据要使用附加依赖项的协议和传输 是必需的。您可以通过指定 附加到基本安装命令。
pip install tinyrpc[httpclient, wsgi]
将安装带有httpclient和wsgi传输依赖项的tinyrpc。
可用的附加功能有:
Option | Needed to use objects of class |
---|---|
gevent | optional in RPCClient, required by RPCServerGreenlets |
httpclient | HttpPostClientTransport, HttpWebSocketClientTransport |
jsonext | optional in JSONRPCProtocol |
websocket | WSServerTransport |
wsgi | WsgiServerTransport |
zmq | ZmqServerTransport, ZmqClientTransport |