
This code sample in python pulls quotes and images from daylife for a given query.
But in a fun way.
from mod_python import apache
from mod_python import util
import urllib
import urllib2
import cjson
import md5
# Base URLs and authentication information
ACCESSKEY = '8befa1cf0a7c0291613242235638a662'
SHARED_SECRET = '2e548ef751397c653752057adcff0c9f'
IMAGE_URL = 'http://freeapi.daylife.com/jsonrest/publicapi/4.1/search_getRelatedImages?include_publication_images=1&limit=10&signature=%s&accesskey=%s&offset=0&query=%s'
QUOTE_URL = 'http://freeapi.daylife.com/jsonrest/publicapi/4.1/search_getRelatedQuotes?limit=7&signature=%s&accesskey=%s&offset=0&query=%s'
def index(req):
request_data = util.FieldStorage(req)
query = request_data.get('query', None)
page_data = get_response(query)
req.content_type = 'text/html'
req.send_http_header()
req.write(str(page_data))
# Creates the appropriate page
def get_response(query):
if query is None:
return BAD_QUERY_PAGE
signature = calc_signature(ACCESSKEY, SHARED_SECRET, query)
quotes = retrieve_daylife_results(QUOTE_URL % (signature, ACCESSKEY, urllib.quote(query)), 'quote')
if len(quotes) == 0:
return NO_DATA_PAGE % (query.upper(), query.capitalize())
image = retrieve_daylife_results(IMAGE_URL % (signature, ACCESSKEY, urllib.quote(query)), 'image')
return generate_result_page(quotes, image, query)
# Gets results from the DayPi
def retrieve_daylife_results(url, result_type):
opener = urllib.urlopen(url)
data = opener.read()
results = cjson.decode(str(data))
# If there was an error with the query, return no results
if results['response']['code'] < 0: return []
# All results from the DayPi are returned nested in a 'payload' object,
# which is nested inside a 'response' object.
return results['response']['payload'][result_type]
# Use the authentication information to generate a query.
def calc_signature(accesskey, sharedsecret, query):
m = md5.new()
m.update(accesskey)
m.update(sharedsecret)
m.update(query)
return m.hexdigest()
# Build the page data
def generate_result_page(quotes, image, query):
page_data = ''+query.upper()+""" SQUAWK BOX
"""
if len(image) > 0:
page_data += '
'
page_data +=' '
for item in quotes:
page_data += '"'+item['quote_text']+'" at '+item['source']['name']+''
page_data += '
'
page_data += '
'
return page_data
BAD_QUERY_PAGE = """Bad query! BAD!!
...WHAT are you looking for?!?"""
NO_DATA_PAGE = """%s IS NO FUN AT ALL
%s - not what the cool kids are into..."""