Created
September 28, 2012 12:27
-
-
Save anderser/3799526 to your computer and use it in GitHub Desktop.
Presidentpoll - get data fra HuffPost president pollofpoll and pass to Django template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 | |
from django.http import HttpResponseRedirect, Http404, HttpResponse | |
from django.template import RequestContext | |
from django.core.cache import cache | |
import iso8601 | |
from pollster import Pollster | |
def presidentmatch(request): | |
#See if we have a resent poll in cache | |
cachedpoll = cache.get('2012-general-election-romney-vs-obama', None) | |
if cachedpoll is None: | |
#This is a cache miss | |
try: | |
pollster = Pollster() | |
#get the latest estimates from Huffington Post API | |
cachedpoll = pollster.chart('2012-general-election-romney-vs-obama') | |
#cache the results for an hour | |
cache.set('2012-general-election-romney-vs-obama', cachedpoll, 60*60) | |
except Exception,e: | |
#when an exception occurs, just show a blank snippet, better than to display an error message inline | |
return HttpResponse("") | |
#format the estimates dict, get just values and replace . with , for Norwegian formatting: | |
estimates = dict([[e['choice'].lower(), str(e['value']).replace(".", ",")] for e in cachedpoll.estimates]) | |
updated = iso8601.parse_date(cachedpoll.last_updated) | |
return render_to_response('presidentpolls/presidentmatch.html', | |
{'estimates': estimates, | |
'updated': updated}, | |
context_instance=RequestContext(request)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment