json-rpc是基于json的跨语言远程调用协议,比xml-rpc、webservice等基于文本的协议传输数据格小,相对hessian、java-rpc等而金种子协议便于调试、实现、扩展,是非常优秀的一种远程调用协议
{
"method": "方法名",
"params": [“参数数组”],
"id": 方法ID
}
{
"jsonrpc": "2.0",
"id": "1234",
"result": null
}
pip install python-jsonprc
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
http_client = pyjsonrpc.HttpClient(
url = "http://example.com/jsonrpc",
username = "Username",
password = "Password"
)
# call方法第一个参数为方法名,后面均为方法的参数
print http_client.call("add", 1, 2) # 3
# 也可直接调用方法传参
print http_client.add(1, 2) # 3
# 发送通知消息给服务器(没有响应请求)
http_client.notify("add", 3, 4)
#!/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()
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
def add(a, b):
"""Test function"""
return a + b
# Handles the JSON-RPC request and gets back the result to STDOUT
pyjsonrpc.handle_cgi_request(methods = dict(add = add))
#!/usr/bin/env python
# coding: utf-8
import pyjsonrpc
class JsonRpc(pyjsonrpc.JsonRpc):
@pyjsonrpc.rpcmethod
def add(self, a, b):
"""Test method"""
return a + b
# 1. 初始化类
rpc = JsonRpc()
# 2. 构造json-rpc的参数
request_json = pyjsonrpc.create_request_json("add", 1, 2)
# 结果为request_json = '{"method": "add", "params": [1, 2], "id": "...", "jsonrpc": "2.0"}'
# 3. 调用jsonrpc方法并获取响应返回值
response_json = rpc.call(request_json)
# response_json = '{"result": 3, "id": "...", "jsonrpc": "2.0"}'
# 4. 将json-rpc字符串转换成python对象
response = pyjsonrpc.parse_response_json(response_json)
# 5. 打印错误
if response.error:
print "Error:", response.error.code, response.error.message
else:
print "Result:", response.result
#!/usr/bin/env python
# coding: utf-8
import cherrypy
from pyjsonrpc.cp import CherryPyJsonRpc, rpcmethod
class Root(CherryPyJsonRpc):
@rpcmethod
def add(self, a, b):
"""Test method"""
return a + b
index = CherryPyJsonRpc.request_handler
print "Starting HTTP server ..."
print "URL: http://localhost:8080"
cherrypy.quickstart(Root())