from bottle import Bottle,request
import httplib2
import json
from google.appengine.api import memcache

bottle = Bottle()
http = httplib2.Http(memcache)

def get_ticker(ticker):
    query = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from"   \
        "%20yahoo.finance.quotes%20where%20symbol%20in%20(%22$TICKER%22)%0A"  \
        "%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org" \
        "%2Falltables.env&callback=".replace("$TICKER", ticker)
    (headers,content) = http.request(query, "GET")
    try:
        return json.loads(content)['query']['results']['quote']
    except:
        return "Unhandled error: " + sys.exc_info()[0]

def print_results(results):
    printable = []
    if not isinstance(results, list):
        results = [results]
    for result in results:
        printable.append( 
            "%s: %s" 
            % (result['symbol'], result['LastTradePriceOnly'])
        )
    return "\n".join(printable)

@bottle.route('/price/<ticker>', method='POST')
def price(ticker):
    return { 'text': print_results(get_ticker(ticker)) }

@bottle.route('/price', method='POST')
def parse():
    trig = request.forms.get('trigger_word')
    text = filter(lambda s: s != '',
                request.forms.get('text')
                .replace(trig, "")
                .replace(","," ")
                .split()
            )
    congrats = "\nYou're gonna be rich, " + request.forms.get('user_name')
    return { 'text': print_results(get_ticker(",".join(text))) + congrats }

# Define an handler for 404 errors.
@bottle.error(404)
def error_404(error):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.'

@@ -527,16 +527,55 @@
  %22GET%22)%0A
+    if headers%5B'status'%5D == '200':%0A    
     try:
@@ -575,16 +575,20 @@
    try:%0A
+    
         
@@ -643,16 +643,20 @@
 quote'%5D%0A
+    
     exce
@@ -663,24 +663,28 @@
 pt:%0A        
+ 
+   
 return %22Unha
@@ -717,16 +717,63 @@
 nfo()%5B0%5D
+%0A    return %22HTTP status: %22 + headers%5B'status'%5D
 %0A%0Adef pr
@@ -906,16 +906,56 @@
 esults:%0A
+        if isinstance(result,list):%0A    
         
@@ -985,16 +985,20 @@
         
+    
 %22%25s: %25s%22
@@ -999,16 +999,20 @@
 s: %25s%22 %0A
+    
         
@@ -1066,16 +1066,20 @@
 Only'%5D)%0A
+    
         
@@ -1562,16 +1562,17 @@
 e rich, 
+@
 %22 + requ
@@ -1603,32 +1603,41 @@
 ')%0A    return %7B 
+%0A        
 'text': print_re
@@ -1680,16 +1680,49 @@
 congrats
+,%0A        'link_names': 1%0A       
  %7D%0A%0A# De

print text returned by Yahoo API