Created
December 27, 2012 18:58
-
-
Save anonymous/4390921 to your computer and use it in GitHub Desktop.
JoeBergantine Home View Cached API Calls (for sharing)
This file contains 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
import json | |
import urllib2 | |
from datetime import datetime | |
from pytz import timezone | |
from django.core.cache import cache | |
from django.views.generic import TemplateView | |
class HomeView(TemplateView): | |
template_name = "home.html" | |
def get_context_data(self, **kwargs): | |
mountain = timezone('US/Mountain') | |
if not cache.get('latest_72ppi'): | |
try: | |
req = urllib2.urlopen('http://72ppi.us/archives/latest.json') | |
latest_72ppi = json.load(req)['entries'][0] | |
latest_72ppi['pub_pyo'] = mountain.localize(datetime.strptime( | |
latest_72ppi['created_at'], '%Y-%m-%dT%H:%M:%S-07:00')) | |
cache.set('latest_72ppi', latest_72ppi, 3600) | |
except: | |
pass | |
if not cache.get('latest_delicious'): | |
try: | |
req = urllib2.urlopen( | |
'http://feeds.delicious.com/v2/json/jbergantine?count=1') | |
latest_delicious = json.load(req)[0] | |
latest_delicious['pub_pyo'] = mountain.localize( | |
datetime.strptime(latest_delicious['dt'], | |
'%Y-%m-%dT%H:%M:%SZ')) | |
cache.set('latest_delicious', latest_delicious, 3600) | |
except: | |
pass | |
if not cache.get('latest_twitter'): | |
try: | |
req = urllib2.urlopen( | |
'https://api.twitter.com/1/statuses/user_timeline.json?'\ | |
'include_entities=true&screen_name=jbergantine'\ | |
'&count=1&exclude_replies=true&include_rts=false') | |
latest_twitter = json.load(req)[0] | |
latest_twitter['pub_pyo'] = mountain.localize( | |
datetime.strptime( | |
latest_twitter['created_at'], | |
'%a %b %d %H:%M:%S +0000 %Y')) | |
cache.set('latest_twitter', latest_twitter, 3600) | |
except: | |
pass | |
# Call the base implementation first to get a context | |
context = super(HomeView, self).get_context_data(**kwargs) | |
# Add in conext objects | |
context['latest_72ppi'] = cache.get('latest_72ppi') | |
context['latest_delicious'] = cache.get('latest_delicious') | |
context['latest_twitter'] = cache.get('latest_twitter') | |
return context |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment