Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Code for Zato article on InfoQ http://www.infoq.com/articles/zato
# anyjson
from anyjson import loads
# bunch
from bunch import bunchify
# decimal
from decimal import Decimal
# lxml
from lxml.objectify import fromstring
# Zato
from zato.server.service import Service
class GetMarketCap(Service):
""" Returns market capitalization value in billion USD by a company's symbol.
"""
class SimpleIO:
response_elem = 'market_cap'
input_required = ('symbol',)
output_required = ('provider', 'value')
def handle(self):
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Yahoo
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Fetch a connection to Y! by its name
yahoo = self.outgoing.plain_http.get('Yahoo! YQL')
# Build URL params to issue a YQL query with.
q = 'select * from yahoo.finance.quotes where symbol="{}"'.format(
self.request.input.symbol)
url_params = {'q':q, 'format':'json', 'env':'http://datatables.org/alltables.env'}
# Invoke Y! and create a bunch instance out of the JSON response so
# we can reference the elements using dot notation.
yahoo_response = bunchify(loads(yahoo.conn.get(self.cid, url_params).text))
# Clean up the response from Y! - chop off the last character if there
# was a business response at all. Assumes the response is always
# in billions.
if yahoo_response.query.results.quote:
value1 = yahoo_response.query.results.quote.MarketCapitalization
value1 = Decimal(value1[:-1]) if value1 else 'n/a'
else:
value1 = 'n/a'
# A new response item is appended to the list of items Zato will
# serialize to JSON or XML, depending on how the service was invoked.
item1 = {'provider':'Yahoo!', 'value': str(value1)}
self.response.payload.append(item1)
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Google
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Fetch a connection to Google by its name
google = self.outgoing.plain_http.get('Google Finance')
# Build URL params to invoke Google with
url_params = {'stock':self.request.input.symbol}
# Invoke Google and create an Objectify instance out of the XML response
# so we can reference the elements using dot notation.
google_response = fromstring(google.conn.get(self.cid, url_params).text)
# Clean up the response from Google - convert from millions to billions
# if there was a business response at all.
if hasattr(google_response.finance, 'market_cap'):
value2 = Decimal(google_response.finance.market_cap.get('data')) / 1000
else:
value2 = 'n/a'
# Again, a plain Python dict (hashmap) is appended to the response object
# and serialization will be done by Zato.
item2 = {'provider':'Google', 'value': str(value2)}
self.response.payload.append(item2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.