Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2012 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4390921 to your computer and use it in GitHub Desktop.
Save anonymous/4390921 to your computer and use it in GitHub Desktop.
JoeBergantine Home View Cached API Calls (for sharing)
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