1、JsonRPC介紹
json-rpc是基於json的跨語言遠程調用協議,比xml-rpc、webservice等基於文本的協議傳輸數據格小;相對hessian、Java-rpc等二進制協議便於調試、實現、擴展,是很是優秀的一種遠程調用協議。python
2、JsonRPC簡單說明
一、調用的Json格式
向服務端傳輸數據格式以下:
{ "method": "方法名", "params": [「參數數組」], "id": 方法ID}web
說明:json
第一個參數: 是方法的名值對數組
第二個參數: 是參數數組框架
第三個參數: 是方法ID(能夠隨意填)url
舉例: { "method": "doSomething", "params": [], "id": 1234}spa
doSomething 是遠程對象的方法, [] 表示參數爲空調試
二、輸出的Json格式
{
"jsonrpc": "2.0",
"id": "1234",
"result": null
}code
3、python-jsonrpc框架
一、安裝
pip install python-jsonrpc
2、例子
http服務端:server
#!/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)