【python】第三方库-python-jsonrpc框架

文章目录

  • JsonRPC简介
    • 调用的json格式
    • 输出的接送格式
  • python-jsonrp框架
    • 安装
    • 简单使用示例
      • HTTP Client 示例
      • HTTP Server 示例
      • CGI(通用网关接口) 示例
      • 框架使用示例
      • CherryPy 示例

JsonRPC简介

json-rpc是基于json的跨语言远程调用协议,比xml-rpc、webservice等基于文本的协议传输数据格小,相对hessian、java-rpc等而金种子协议便于调试、实现、扩展,是非常优秀的一种远程调用协议

调用的json格式

{ 
    "method": "方法名", 
    "params": [“参数数组”],
    "id":  方法ID
}

输出的接送格式

{
  "jsonrpc": "2.0",
  "id": "1234",
  "result": null
}

python-jsonrp框架

  • 目前仅支持python2
  • 官方文档:https://pypi.org/project/python-jsonrpc/
  • git地址:https://github.com/gerold-penz/python-jsonrpc

安装

pip install python-jsonprc

简单使用示例

HTTP Client 示例

#!/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)

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()

CGI(通用网关接口) 示例

#!/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

CherryPy 示例

#!/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())

你可能感兴趣的:(python,jsonrpc,python-jsonrpc,python)