04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

338 CHAPTER 15 ■ PYTHON AND THE WEB<br />

>>> from xmlrpclib import ServerProxy<br />

>>> server = ServerProxy('http://coversproject.com/RPC.php')<br />

>>> covers = server.covers.Covered('Monty Python')<br />

>>> for cover in covers:<br />

... if cover['song'] == 'Brave Sir Robin':<br />

... print cover['artist']<br />

...<br />

Happy Rhodes<br />

The ServerProxy object looks like a normal object with various methods you can call, but<br />

in fact, whenever you call one of its methods, it sends a request to the server, which responds<br />

to the requests and returns an answer. So, in a way, you’re calling the method covers.Covered<br />

on the server itself. Network programming could hardly be any easier than this. (For more<br />

information about the XML-RPC methods supplied by The Covers Project, see http://<br />

coversproject.com/about/xmlrpc.html.)<br />

■Note XML-RPC procedure (function/method) names may contain dots, as in the preceding example. The<br />

name covers.Covered does not imply the existence of an object named covers on the server—the dots<br />

are only used to structure the names.<br />

Here is a slightly more complicated example, which uses the news service Meerkat to find<br />

some articles about Python:<br />

>>> from xmlrpclib import ServerProxy<br />

>>> query = {'search': 'Python', 'num_items': 5}<br />

>>> s = ServerProxy('http://www.oreillynet.com/meerkat/xml-rpc/server.php')<br />

>>> items = s.meerkat.getItems(query)<br />

>>> [i['title'] for i in items]<br />

['MacHack: Meet Dylan the Yoot', 'Hap Debugger', 'Project and proposal for<br />

integrating validation with processing pipelines', 'Spam Check', 'ZCoMIX 1.0<br />

Final Released']<br />

>>> items[0].keys()['link', 'description', 'title']<br />

>>> items[3]['link']<br />

'http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134945'<br />

As you can see, the method meerkat.getItems is called with a mapping parameter that<br />

contains various arguments (in this case a search query and the number of items to be returned)<br />

and returns a list of mappings, each of which has a title, a description, and a link. Actually,<br />

there is a lot more to Meerkat than this—if you want to experiment, take a look at the Meerkat<br />

Web site (http://www.oreillynet.com/meerkat) or one of the many online tutorials about<br />

the Meerkat XML-RPC API (for example, http://oreillynet.com/pub/a/rss/2000/11/14/<br />

meerkat_xmlrpc.html).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!