python json-rpc客户机服务器库-使用python jsonrpc库很简单

python-jsonrpc的Python项目详细描述


https://travis-ci.org/gerold-penz/python-jsonrpc.svg?branch=master

安装

pip install python-jsonrpc

http客户端示例

#!/usr/bin/env python# coding: utf-8importpyjsonrpchttp_client=pyjsonrpc.HttpClient(url="http://example.com/jsonrpc",username="Username",password="Password")printhttp_client.call("add",1,2)# Result: 3# It is also possible to use the *method* name as *attribute* name.printhttp_client.add(1,2)# Result: 3# Notifications send messages to the server, without response.http_client.notify("add",3,4)

http服务器示例

#!/usr/bin/env python# coding: utf-8importpyjsonrpcclassRequestHandler(pyjsonrpc.HttpRequestHandler):@pyjsonrpc.rpcmethoddefadd(self,a,b):"""Test method"""returna+b# Threading HTTP-Serverhttp_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-8importpyjsonrpcdefadd(a,b):"""Test function"""returna+b# Handles the JSON-RPC request and gets back the result to STDOUTpyjsonrpc.handle_cgi_request(methods=dict(add=add))

库使用示例

#!/usr/bin/env python# coding: utf-8importpyjsonrpcclassJsonRpc(pyjsonrpc.JsonRpc):@pyjsonrpc.rpcmethoddefadd(self,a,b):"""Test method"""returna+b# 1. Initialize JSON-RPC classrpc=JsonRpc()# 2. Create JSON-RPC string with parameters (= request string)request_json=pyjsonrpc.create_request_json("add",1,2)# request_json = '{"method": "add", "params": [1, 2], "id": "...", "jsonrpc": "2.0"}'# 3. Call the JSON-RPC function and get back the JSON-RPC result (= response string)response_json=rpc.call(request_json)# response_json = '{"result": 3, "id": "...", "jsonrpc": "2.0"}'# 4. Convert JSON-RPC string to Python objectsresponse=pyjsonrpc.parse_response_json(response_json)# 5. Print result or errorifresponse.error:print"Error:",response.error.code,response.error.messageelse:print"Result:",response.result

樱桃色示例

#!/usr/bin/env python# coding: utf-8importcherrypyfrompyjsonrpc.cpimportCherryPyJsonRpc,rpcmethodclassRoot(CherryPyJsonRpc):@rpcmethoddefadd(self,a,b):"""Test method"""returna+bindex=CherryPyJsonRpc.request_handlerprint"Starting HTTP server ..."print"URL: http://localhost:8080"cherrypy.quickstart(Root())

许可证

  • GNU库或更低的通用公共许可证(LGPL)
  • 麻省理工学院许可证

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java本机方法的源代码可用吗?   java如何使父方法抛出异常?   java Android以编程方式设置不同屏幕大小/密度的布局   java如何使用一个变量来管理所有客户端请求   java输入一个txt文件,每行有一组数字   json java从jsonobject获取jsonarray错误   java将一个(WAV)写入一个文件只会说一个单词(最后一个单词)   java Telnet忽略原始字节   proguard java。运行桌面应用程序时出现lang.VerifyError   java用左键移动JLabel?   java如何在jText区域验证选项卡?   文件服务器客户端Javasocket编程中的字符串搜索   java省略了JSTL中的最后一个逗号<c:out>   java如何找到if或else代码已执行的次数?   java JavaScript WebSocket send()方法未执行   浮点数声明上的java标识符预期错误   java这是指二进制搜索算法吗?   编译mod at:reobfJar java时的minecraft问题。util。拉链ZipException:重复条目   java检测特定的震动运动(如图所示:D)