15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

23.1. Web Services<br />

There are many Web services and applications on the Net, providing a wide variety of services. You will<br />

find application programmer interfaces (APIs) from most of the big players today, i.e., Yahoo!, Google,<br />

eBay, and Amazon, to name a few. In the past, APIs have been used just to access data using these<br />

services; however, today's APIs are different. They are rich and fully featured, and you are able to<br />

actually integrate services into your own personal Web sites and Web pages, commonly known as "Mashups."<br />

This is an area of active interest that we will continue to explore (REST, XML, RSS, etc.), but for now,<br />

we are going to take a trip back in time to play around with an older interface that is both useful and<br />

has longevity, the stock quote server from Yahoo! at http://finance.yahoo.com.<br />

23.1.1. Yahoo! Finance Stock Quote Server<br />

If you visit the Web site and pull up a quotation for any stock, you will find a Uniform Resource Locator<br />

(URL) link under the basic quote data labeled "Download Data," which lets users download a CSV file<br />

suitable for importing into Microsoft Excel or Intuit Quicken:<br />

http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgv&e=.csv<br />

If your browser's MIME settings are set correctly, your browser will actually launch Excel with the<br />

resulting data. This is due primarily to the final variable (key-value) pair found in the link, e=.csv. This<br />

variable is actually not used by the server as it always sends back data in CSV format anyway.<br />

If we use our friend urllib.urlopen(), we see that for any stock ticker symbol, one CSV string is<br />

returned:<br />

>>> from urllib import urlopen<br />

>>> u = urlopen('http://quote.yahoo.com/d/<br />

quotes.csv?s=YHOO&f=sl1d1t1c1ohgv')<br />

>>> for row in u:<br />

... print 'row'<br />

...<br />

'"YHOO",30.76,"5/23/<br />

2006","4:00pm",+0.30,31.07,31.63,30.76,28594020\r\n'<br />

>>> f.close()<br />

The string would then have to be manually parsed (by stripping the trailing whitespace and splitting on<br />

the comma delimiter). As an alternative to parsing the data string ourselves, we can use the csv<br />

module, introduced in <strong>Python</strong> 2.3, which does both the string split and the whitespace strip. Using csv,<br />

we can replace the for loop above with the following assuming all other lines are left intact:<br />

>>> import csv<br />

>>> for row in csv.reader(u):<br />

... print row<br />

...

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

Saved successfully!

Ooh no, something went wrong!