python-jsonrpc框架实现JsonRPC协议的web服务

一、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)

  

posted @ 2018-05-25 15:21  lzp的bky  阅读(9220)  评论(2编辑  收藏  举报