一、JsonRPC介紹
json-rpc是基於json的跨語言遠程調用協議,比xml-rpc、webservice等基於文本的協議傳輸數據格小;相對hessian、Java-rpc等二進制協議便於調試、實現、擴展,是非常優秀的一種遠程調用協議。
二、JsonRPC簡單說明
1、調用的Json格式
向服務端傳輸數據格式如下:
{ "method": "方法名", "params": [“參數數組”], "id": 方法ID}
說明:
第一個參數: 是方法的名值對
第二個參數: 是參數數組
第三個參數: 是方法ID(可以隨意填)
舉例: { "method": "doSomething", "params": [], "id": 1234}
doSomething 是遠程對象的方法, [] 表示參數為空
2、輸出的Json格式
{
"jsonrpc": "2.0",
"id": "1234",
"result": null
}
三、python-jsonrpc框架
1、安裝
pip install python-jsonrpc
2、例子
http服務端:
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
class RequestHandler(pyjsonrpc.HttpRequestHandler):
@pyjsonrpc.rpcmethod
def add(self, a, b):
"""Test method"""
return a + b
# Threading HTTP-Server
http_server = pyjsonrpc.ThreadingHttpServer(
server_address = ('localhost', 8080),
RequestHandlerClass = RequestHandler
)
print "Starting HTTP server ..."
print "URL: http://localhost:8080"
http_server.serve_forever()
http客戶端:
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
http_client = pyjsonrpc.HttpClient(
url = "http://example.com/jsonrpc",
username = "Username",
password = "Password"
)
print http_client.call("add", 1, 2)
# Result: 3
# It is also possible to use the *method* name as *attribute* name.
print http_client.add(1, 2)
# Result: 3
# Notifications send messages to the server, without response.
http_client.notify("add", 3, 4)
