文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
::-- ["huangyi"] [DateTime(2006-04-22T18:48:25Z)] TableOfContents
描述
问题 Problem
你需要向一个 XML-RPC 服务器发起一个方法调用
You need to make a method call to an XML-RPC server.
解决 Solution
xmlrpclib 包使得编写 XML-RPC 客户端非常容易。比如, 我们可以使用 XML-RPC 来访问 O'Reilly's Meerkat 服务并获取五条最新的关于 Python 有关的信息:
The xmlrpclib package makes writing XML-RPC clients very easy. For example, we can use XML-RPC to access O'Reilly's Meerkat server and get the five most recent items about Python:
讨论 Discussion
XML-RPC is a simple and lightweight approach to distributed processing. xmlrpclib, which makes it easy to write XML-RPC clients and servers in Python, has been part of the core Python library since Python 2.2, but you can also get it for older releases of Python from http://www.pythonware.com/products/xmlrpc/.
To use xmlrpclib, instantiate a proxy to the server (the ServerProxy class, also known as the Server class for backward compatibility) by passing in the URL to which you want to connect. Then, on that instance, access whatever methods the remote XML-RPC server supplies. In this case, you know that Meerkat supplies a getItems method, so if you call the method of the same name on the server-proxy instance, the instance relays the call to the server and returns the results.
This recipe uses O'Reilly's Meerkat service, intended for the syndication of contents such as news and product announcements. Specifically, the recipe queries Meerkat for the five most recent items mentioning either "Python" or "python". If you try this, be warned that, depending on the quality of your Internet connection, the time of day, and the level of traffic on the Internet, response times from Meerkat are variable. If the script takes a long time to answer, it doesn't mean you did something wrong, it just means you have to be patient!
Using xmlrpclib by passing raw dictionaries is quite workable, but rather unPythonic. Here's an easy alternative that looks quite a bit nicer:
from xmlrpclib import Server server = Server("http://www.oreillynet.com/meerkat/xml-rpc/server.php")
class MeerkatQuery:
- def _ _init_ _(self, search, num_items=5, descriptions=0):
- self.search = search self.num_items = num_items self.descriptions = descriptions
q = MeerkatQuery("[Pp]ython") print server.meerkat.getItems(q) Of course, you can package the instance attributes and their default values in several different ways, but the point of this variation is that, as the argument to the getItems method, an instance object with the right attributes works just as well as a dictionary object with the same information packaged as dictionary items.
参考 See Also
The XML-RPC library ships with recent versions of Python; if it isn't in your version of Python, you can get it from http://www.pythonware.com/products/xmlrpc/; Meerkat is at http://www.oreillynet.com/meerkat/.