當前位置:
首頁 >
python-jsonrpc框架实现JsonRPC协议的web服务
發布時間:2025/7/14
30
豆豆
生活随笔
收集整理的這篇文章主要介紹了
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-jsonrpc2、例子
http服務端:
#!/usr/bin/env python # coding: utf-8import pyjsonrpcclass RequestHandler(pyjsonrpc.HttpRequestHandler):@pyjsonrpc.rpcmethoddef 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-8import pyjsonrpchttp_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)
轉載于:https://www.cnblogs.com/liangzp/p/9088792.html
總結
以上是生活随笔為你收集整理的python-jsonrpc框架实现JsonRPC协议的web服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wget命令【转】
- 下一篇: python入门第二天__练习题