Python XML RPC服务器端和客户端实例

yipeiwu_com4年前服务器

一、远程过程调用RPC

XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire.

简单地,client可以调用server上提供的方法,然后得到执行的结果。类似与webservice。

推荐查看xmlprc的源文件:C:\Python31\Lib\xmlrpc

二、实例

1) Server

复制代码 代码如下:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

def div(x,y):
    return x - y
   
class Math:
    def _listMethods(self):
        # this method must be present for system.listMethods
        # to work
        return ['add', 'pow']
    def _methodHelp(self, method):
        # this method must be present for system.methodHelp
        # to work
        if method == 'add':
            return "add(2,3) => 5"
        elif method == 'pow':
            return "pow(x, y[, z]) => number"
        else:
            # By convention, return empty
            # string if no help is available
            return ""
    def _dispatch(self, method, params):
        if method == 'pow':
            return pow(*params)
        elif method == 'add':
            return params[0] + params[1]
        else:
            raise 'bad method'

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_introspection_functions()
server.register_function(div,"div")
server.register_function(lambda x,y: x*y, 'multiply')
server.register_instance(Math())
server.serve_forever()

2)client

复制代码 代码如下:

import xmlrpc.client

s = xmlrpc.client.ServerProxy('http://localhost:8000')

print(s.system.listMethods())

print(s.pow(2,3))  # Returns 28
print(s.add(2,3))  # Returns 5
print(s.div(3,2))  # Returns 1
print(s.multiply(4,5)) # Returns 20

3)result

相关文章

Python Web服务器Tornado使用小结

首先想说的是它的安全性,这方面确实能让我感受到它的良苦用心。这主要可以分为两点: 一、防范跨站伪造请求(Cross-site request forgery,简称 CSRF 或 XSRF...

python远程连接服务器MySQL数据库

本文实例为大家分享了python远程连接服务器MySQL数据库的具体代码,供大家参考,具体内容如下 这里默认大家都已经配置安装好 MySQL 和 Python 的MySQL 模块,且默认...

Python实现多线程/多进程的TCP服务器

多线程的TCP服务器,供大家参考,具体内容如下 背景:同学公司的传感器设备需要将收集的数据发到服务器上,前期想写一个简单的服务器来测试下使用效果,设备收集的数据非常的重要,所以考虑使用T...

深入Memcache的Session数据的多服务器共享详解

一相关介绍1.memcache + memcache的多服务器数据共享的介绍,请参见http://www.guigui8.com/index.php/archives/206.html2...

Apache服务器下防止图片盗链的办法

先解释一下图片防盗链和转向:   图片防盗链有什么用?   防止其它网站盗用你的图片,浪费你宝贵的流量。   图片转向有什么用?   如果你的网站以图片为主,哪天发现月底...