RPC/rpc:Python实现简单rpc代码

 

1. server.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
''' 
@Author: Victor
@Date: 2020/7/31
@function: ''
'''

from twisted.web import xmlrpc, server
from twisted.internet import reactor


class Test(xmlrpc.XMLRPC):

    def xmlrpc_add(self, a, b):
        return a + b

    def common_subtract(self, a, b):
        return a - b

    def xmlrpc_fault(self):
        raise xmlrpc.Fault(123, "The fault procedure is faulty.")


if __name__ == '__main__':
    print("start:")

    obj = Test()
    reactor.listenTCP(7080, server.Site(obj))
    reactor.run()

2. client.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
''' 
@Author: Victor
@Date: 2020/7/31
@function: ''
'''

import xmlrpc.client

with xmlrpc.client.ServerProxy("http://localhost:7080/") as proxy:
    print("Sum is : %s" % str(proxy.add(3, 4)))
    # 7
    print("Difference is : %s" % str(proxy.common_subtract(3, 4)))
    # xmlrpc.client.Fault: < Fault8001: 'procedure common_subtract not found' >

  

结果是:

D:\software\anaconda_dir\python.exe D:/TheCode/practice/rpc_check/client.py
Traceback (most recent call last):
File "D:/TheCode/practice/rpc_check/client.py", line 13, in <module>
print("Difference is : %s" % str(proxy.common_subtract(3, 4)))
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 1452, in __request
verbose=self.__verbose
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 1170, in single_request
return self.parse_response(resp)
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 1342, in parse_response
return u.close()
File "D:\software\anaconda_dir\lib\xmlrpc\client.py", line 656, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 8001: 'procedure common_subtract not found'>

比较上下两种结果
Sum is : 7

Process finished with exit code 1

 

posted @ 2020-07-31 14:05  Adamanter  阅读(193)  评论(0)    收藏  举报