当前位置:首页 >> 脚本专栏

python远程调用rpc模块xmlrpclib的方法

RPC(Remote Procedure Call Protocol)是远程调用协议,它通过网络请求服务到远端服务器,服务器根据请求做出响应,将结果返回

它是一种C/S模式,客户端可以调用远程服务器上的参数(类似URL)并返回结果

利用rpc可以实现系统的分布式架构,可以将功能分解到多台服务器上进行实现,同时也将也可以将负载打散,分布到不同服务器上,整合计算资源

在openstack中就大量使用了rpc

rpc多使用http传输请求,格式有xml,json等,这里是xml

模块:

xmlrpclib

注:xmlrpclib模块在python3中重命名为xmlrpc.client

xmlrpc并不是很安全,但在2.7.9 https url中默认加入了证书,主机名验证

定义:

class xmlrpclib.ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime[, context]]]]]])

1.uri,即服务端的url地址

2.transport 传输实例,可选,https urls/http

3.encoding

4.verbose 是debug模式

5.allow_none 是否请求空 ,若为True,那么常量none将被翻译成xml,默认如果是none则抛出异常 TypeError

6.use_datetime 可以使用date/time values记录调用时间datetime.datetime,默认是false

ServerProxy对象提供一些默认的方法:

1.ServerProxy.system.listMethods() 返回远端服务器方法列表

2.ServerProxy.system.methodSignature(name) 方法签名,是一个数组类型

3.ServerProxy.system.methodHelp(name) 方法帮助信息

例如一个简单的示例:

服务端:

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer

def get_power(n,m):
 return n**m

server = SimpleXMLRPCServer(("0.0.0.0", 8081))
print "start service get power on 0.0.0.0 8081..."
server.register_function(get_power, "get_power")
server.serve_forever()

客服端:

import xmlrpclib

server_power = xmlrpclib.ServerProxy("http://192.168.137.9:8081/")
print "3**2 = %d" %(server_power.get_power(3,2))
print "2**5 = %d" %(server_power.get_power(2,5))

结果:

服务端:

# python xml_server.py 
start service get power on 0.0.0.0 8081...

192.168.137.9 - - [22/May/2017 10:37:47] "POST / HTTP/1.1" 200 -
192.168.137.9 - - [22/May/2017 10:37:47] "POST / HTTP/1.1" 200 -

客服端:

# python xml_client.py 
3**2 = 9
2**5 = 32

xmlrpclib提供的一些方法:

class xmlrpclib.DateTime 时间对象

例如:

服务端:

import datetime
from SimpleXMLRPCServer import SimpleXMLRPCServer
import xmlrpclib

def today():
 today = datetime.datetime.today()
 return xmlrpclib.DateTime(today)

server = SimpleXMLRPCServer(("0.0.0.0", 8081))
print "start service on 0.0.0.0 8081..."
server.register_function(today, "today")
server.serve_forever()

客服端:

import xmlrpclib
import datetime

s = xmlrpclib.ServerProxy("http://192.168.137.9:8081/")

today = s.today()
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")

结果:

服务端

# python rpc_time.py 
start service on 0.0.0.0 8081...

192.168.137.9 - - [22/May/2017 10:43:19] "POST / HTTP/1.1" 200 -

客服端:

# python rpc_time_client.py 
Today: 22.05.2017, 10:43

2.class xmlrpclib.Binary 二进制对象

3.class xmlrpclib.Fault fault对象

如:

客服端:

import xmlrpclib

s = xmlrpclib.ServerProxy("http://192.168.137.9:8081/")
try:
 s.add(2, 5)
except xmlrpclib.Fault as err:
 print "A fault occurred"
 print "Fault code: %d" % err.faultCode
 print "Fault string: %s" % err.faultString

class xmlrpclib.MultiCall(server) 提供多个调用,复合调用:

例如:

from SimpleXMLRPCServer 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

def get_power(n,m):
 return n**m

server = SimpleXMLRPCServer(("0.0.0.0", 8081))
print "start service on 0.0.0.0 8081..."

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.register_function(get_power, 'get_power')
server.serve_forever() 

客服端:

import xmlrpclib

s = xmlrpclib.ServerProxy("http://192.168.137.9:8081/")
multicall = xmlrpclib.MultiCall(s)
multicall.add(7,3)
multicall.subtract(7,3)
multicall.multiply(7,3)
multicall.divide(7,3)
multicall.get_power(7,3)
result = multicall()

print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d 7**3=%d" % tuple(result)

服务端:

# python mul_xmlserver.py 
start service on 0.0.0.0 8081...

192.168.137.9 - - [22/May/2017 10:51:59] "POST / HTTP/1.1" 200 -

客服端:

# python mul_xmlclient.py 
7+3=10, 7-3=4, 7*3=21, 7/3=2 7**3=343

另外xmlrpc还提供有比较快捷的函数:

1.xmlrpclib.boolean(value) 将任意的python值转换成xmlrpc的布尔类型True/False

2.xmlrpclib.dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]])

params请求转换为xml

3.xmlrpclib.loads(data[, use_datetime])

将一个xml-rpc的请求转换成python对象

例如:

from xmlrpclib import ServerProxy, Error

server = ServerProxy("http://betty.userland.com")

print server

try:
 print server.examples.getStateName(41)
except Error as err:
 print "ERROR", err

客服端:

import xmlrpclib, httplib

class ProxiedTransport(xmlrpclib.Transport):
 def set_proxy(self, s):
  self.s = s

 def make_connection(self, host):
  self.realhost = host
  h = httplib.HTTPConnection(self.s)
  return h

 def send_request(self, connection, handler, request_body):
  connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))

 def send_host(self, connection, host):
  connection.putheader('Host', self.realhost)

p = ProxiedTransport()
p.set_proxy('proxy-server:8080')
server = xmlrpclib.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p)
print server.currentTime.getCurrentTime()

以上这篇python远程调用rpc模块xmlrpclib的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。