Python XML-RPC

来源:互联网 发布:淘宝买止咳水的暗语 编辑:程序博客网 时间:2024/05/20 16:13

XML-RPC

xmlrpc是使用http协议做为传输协议的rpc机制,使用xml文本的方式传输命令和数据。

一个rpc系统,必然包括2个部分:

1)rpc client,用来向rpc server调用方法,并接收方法的返回数据;

2)rpc server,用于响应rpc client的请求,执行方法,并回送方法执行结果。

RPC是Remote Procedure Call的缩写,翻译成中文就是远程过程调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算”,是为了提高各个分立机器的“互操作性”而发明出来的技术。

以上内容摘自:百度百科

 

xmlrpc的好处:

1. 传输复杂的数据。

2. 通过程序语言的封装,实现远程对象的调用。

 

一个示例:

view plaincopy to clipboardprint?
  1. # The server code  
  2. from SimpleXMLRPCServer import SimpleXMLRPCServer  
  3.   
  4. def is_even(n):  
  5.     return n%2 == 0  
  6.   
  7. server = SimpleXMLRPCServer(("localhost"8000))  
  8. print "Listening on port 8000..."  
  9. server.register_function(is_even, "is_even")  
  10. server.serve_forever()  

 

view plaincopy to clipboardprint?
  1. # The client code  
  2. import xmlrpclib  
  3.   
  4. proxy = xmlrpclib.ServerProxy("http://localhost:8000/")  
  5. print "3 is even: %s" % str(proxy.is_even(3))  
  6. print "100 is even: %s" % str(proxy.is_even(100))  

 

支持传输的数据类型:

NameMeaningbooleanThe True and False constantsintegersPass in directlyfloating-point numbersPass in directlystringsPass in directlyarraysAny Python sequence type containing conformable elements. Arrays are returned as listsstructuresA Python dictionary. Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their __dict__ attribute is transmitted.datesin seconds since the epoch (pass in an instance of the DateTime class) or a datetime.datetimeinstance.binary datapass in an instance of the Binary wrapper class

 

xmlrpc能用来干啥?

开发API。

大名鼎鼎的WordPress就有xmlrpc接口,比如,可以用于该接口发布文章。想了解更多可以看这篇文章 http://blog.bluesky.cn/archives/466/using-xml-rpc-protocol-to-read-and-write-articles-on-wordpress.html,我还找到了封装非常好的库wordpresslib(http://www.blackbirdblog.it/programmazione/progetti/28)。

 

参考文章:

http://docs.python.org/library/xmlrpclib.html

http://en.wikipedia.org/wiki/XML-RPC

http://www.cnblogs.com/coderzh/archive/2008/12/03/1346994.html

原创粉丝点击