• python rpc


    参考:https://www.cnblogs.com/ExMan/p/10408353.html

    用python的rpc库SimpleXMLRPCServer 做测试,创建rpc server,然后注册一些函数,供应别的客户端去调用

    rpc_server.py:

    from xmlrpc.server import SimpleXMLRPCServer
    
    
    def add(x, y):
    	return x + y
    
    
    def subtract(x, y):
    	return x - y
    
    
    def multiply(x, y):
    	return x * y
    
    
    def divide(x, y):
    	return x // y
    
    
    server = SimpleXMLRPCServer(('127.0.0.1', 8080))
    print('listening on port 8080')
    
    server.register_multicall_functions()
    server.register_function(add, 'add')
    server.register_function(subtract, 'subtract')
    server.register_function(multiply, 'multiply')
    server.register_function(divide, 'divide')
    
    server.serve_forever()
    

    rpc_client.py:

    from xmlrpc.client import ServerProxy, MultiCall
    
    proxy = ServerProxy(('http://127.0.0.1:8080'))
    
    multicall = MultiCall(proxy)
    
    multicall.add(5, 3)
    multicall.subtract(5, 3)
    multicall.multiply(5, 3)
    multicall.divide(5, 3)
    result = multicall()
    
    print("5+3=%d, 5-3=%d, 5*3=%d, 5//3=%d" % tuple(result))
    

    RPC本来是单任务的,如果任务相对频繁,可以设置成多线程的默认,你不用在调用threading模块什么的,直接引用:

    rpc_thread_server.py:

    from xmlrpc.server import SimpleXMLRPCServer
    from socketserver import ThreadingMixIn
    
    
    class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
    	pass
    
    
    def add(x, y):
    	return x + y
    
    
    def subtract(x, y):
    	return x - y
    
    
    def multiply(x, y):
    	return x * y
    
    
    def divide(x, y):
    	return x // y
    
    
    server = ThreadXMLRPCServer(('127.0.0.1', 8080), allow_none=True)  # 初始化
    print('listening on port 8080')
    
    server.register_multicall_functions()
    server.register_function(add, 'add')
    server.register_function(subtract, 'subtract')
    server.register_function(multiply, 'multiply')
    server.register_function(divide, 'divide')
    
    server.serve_forever()
    

    rpc_client.py不变。

    ---------------另外-------------------
    server = SimpleXMLRPCServer.SimpleXMLRPCServer((srv_conf[‘host’], srv_conf[‘port’]), allow_none=True)
    添加allow_none=True防止出错:xmlrpc.client.Fault: <Fault 1: "<class 'TypeError'>:cannot marshal None unless allow_none is enabled">

  • 相关阅读:
    鼠标放上面有提示
    js-行事件
    angularjs----实现切换,显示隐藏,选中一行不是table
    [2015-10-28]点击隐藏和显示-jquery和样式
    [2015-10-28]Angularjs-----数据获取,关联
    [2015-10-28]表格排序----question
    [2015-10-27]前端导出excel
    Kafka设计解析(一)- Kafka背景及架构介绍
    JAVA加解密
    kafka入门
  • 原文地址:https://www.cnblogs.com/lovebkj/p/12912074.html
Copyright © 2020-2023  润新知