Skip to content

Commit

Permalink
Merged in mk200789/django-hackathon-starter (pull request DrkSephy#21)
Browse files Browse the repository at this point in the history
instagram template + views + script
  • Loading branch information
DrkSephy committed Apr 12, 2015
2 parents fd47c7e + b04e75d commit 29174eb
Show file tree
Hide file tree
Showing 8 changed files with 159 additions and 45 deletions.
60 changes: 60 additions & 0 deletions hackathon_starter/hackathon/scripts/instagram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import requests
import urllib
import urllib2
import json
import simplejson as json2

authorization_url = 'https://api.instagram.com/oauth/authorize/?client_id='
access_token_url = 'https://api.instagram.com/oauth/access_token'

class InstagramOauthClient(object):

access_token = None
user_data = None

def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret

def get_authorize_url(self):
''' Obtains the authorization url. '''
auth_url = authorization_url + self.client_id +'&redirect_uri=http://localhost:8000/hackathon/instagram&response_type=code'
return auth_url

def get_access_token(self, code):
''' Obtains access token. '''

auth_setting = {'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'redirect_uri': 'http://localhost:8000/hackathon/instagram',
'code': code
}

auth_setting_url = urllib.urlencode(auth_setting)
req = urllib2.Request(access_token_url, auth_setting_url)
content = urllib2.urlopen(req)
jsonlist = json.load(content)
self.access_token = jsonlist['access_token']
self.user_data = jsonlist['user']
print self.access_token


def get_tagged_media(self, tag):
''' Get recent tagged media. '''
tagged_media_url = 'https://api.instagram.com/v1/tags/'+tag+'/media/recent?access_token='+self.access_token# +'&count=2'
req = requests.get(tagged_media_url)
content = json2.loads(req.content)
data = content['data']

while len(data) <= 100:
next_url= content['pagination']['next_url']
req = requests.get(next_url)
content = json2.loads(req.content)
for i in content['data']:
data.append(i)
print len(data)
return data



51 changes: 24 additions & 27 deletions hackathon_starter/hackathon/scripts/tumblr.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,59 +10,54 @@
request_token_url = 'http://www.tumblr.com/oauth/request_token'
authorize_url = 'http://www.tumblr.com/oauth/authorize'
access_token_url = 'http://www.tumblr.com/oauth/access_token'

user_uri = "http://api.tumblr.com/v2/user/info"
blog_uri = "http://api.tumblr.com/v2/blog/"

class TumblrOauthClient(object):

token = None
oauth_token_secret = None
oauth_verifier = None
oauth_token = None
oauth_token_secret = None
accessed = False


def __init__(self, consumer_key, consumer_secret, oauth_token =''):

def __init__(self, consumer_key, consumer_secret):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.consumer = oauth2.Consumer(consumer_key, consumer_secret)
self.oauth_token = oauth_token



def get_authorize_url(self):
def authorize_url(self):
client = oauth2.Client(self.consumer)
resp, content = client.request(request_token_url, "GET")

#if int(resp['status']) != 200:
# raise Exception("Invalid response %s." % resp['status'])

#parse content
if not self.oauth_token:
request_token = dict(urlparse.parse_qsl(content))
self.oauth_token = request_token['oauth_token'] #'QBXdeeMKAnLzDbIG7dDNewTzRYyQoHZLbcn3bAFTCEFF5EXurl'
self.oauth_token_secret = request_token['oauth_token_secret']#'u10SuRl2nzS8vFK4K7UPQexAvbIFBFrZBjA79XDlgoXFxv9ZhO'

self.oauth_token = request_token['oauth_token'] #'QBXdeeMKAnLzDbIG7dDNewTzRYyQoHZLbcn3bAFTCEFF5EXurl' #
self.oauth_token_secret = request_token['oauth_token_secret']#'u10SuRl2nzS8vFK4K7UPQexAvbIFBFrZBjA79XDlgoXFxv9ZhO' #
link = authorize_url+"?oauth_token="+self.oauth_token+"&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/tumblr"
return link

#"""

def get_access_token_url(self, oauth_verifier):
#print "verifier"
self.oauth_verifier = oauth_verifier
def access_token_url(self, oauth_verifier=''):
self.accessed = True
token = oauth2.Token(self.oauth_token, self.oauth_token_secret)
self.oauth_verifier = oauth_verifier
print self.oauth_verifier
token.set_verifier(self.oauth_verifier)

client = oauth2.Client(self.consumer, token)
resp, content = client.request(access_token_url,"POST")

#print resp['status']

access_token = dict(urlparse.parse_qsl(content))
#print access_token

#set verified token
self.token = oauth2.Token(access_token['oauth_token'], access_token['oauth_token_secret'])
#print self.token




def getUserInfo(self):
''' Returns users information. '''
client = oauth2.Client(self.consumer, self.token)
Expand All @@ -75,25 +70,27 @@ def getUserInfo(self):
jsonlist = json.loads(content)
response = jsonlist['response']
user_info = response['user']
total_blogs = len(user_info['blogs'])
#print user_info
return user_info
return user_info, total_blogs


def getBlogInfo(self, user):
''' Returns blogger's blog information '''
blog_info = blog_uri + user + ".tumblr.com/info?api_key="+self.consumer_key
req = requests.get(blog_info)

if int(req.status_code) != 200:
raise Exception("Invalid response %s." % resp['status'])
#if int(req.status_code) != 200:
# raise Exception("Invalid response %s." % resp['status'])


jsonlist = json.loads(req.content)
response = jsonlist['response']
blog = response['blog']
blog['updated'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(blog['updated']))

return blog


def getTaggedInfo(self, tag):
''' Return tags related to blog with certain tag. '''

Expand All @@ -116,6 +113,7 @@ def getTaggedInfo(self, tag):

return tags


def getTaggedBlog(self, tag):
''' Return the tagged blogs's captions or post.'''

Expand Down Expand Up @@ -147,4 +145,3 @@ def getTaggedBlog(self, tag):
tagtext.append(text)

return tagtext
#"""
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<div class="col-sm-4"><a href={{tumblr_url}}>Tumblr Example</a></div>
<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/linkedin/">LinkedIn Example</a></div>
<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twilio/">Twilio Example</a></div>
<div class="col-sm-4"><a href="{{instagram_url}}">Instagram Example</a></div>

</div>

Expand Down
17 changes: 17 additions & 0 deletions hackathon_starter/hackathon/templates/hackathon/instagram.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<body>
{% include 'hackathon/base.html' %}
<h1 class="text-center"> {{ title }}</h1>
<br>
<div class="col-lg-12">
<div class="table-responsive">
<h2> #{{search_tag}} </h2>
<table class="table">
{% for i in tagged_media %}
<img src="{{i.images.thumbnail.url}}">
{% endfor %}
</table>
</div>
</div>
</html>
15 changes: 15 additions & 0 deletions hackathon_starter/hackathon/templates/hackathon/tumblr.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,20 @@ <h2> Comments </h2>
</table>
</div>
</div>
<div class="col-md-4">
<div class="table-responsive">
<h2> User's Info </h2>
<table class="table table-bordered">
<tr>
<th>Name</th>
<td>{{userinfo.name}}</td>
</tr>
<tr>
<th>Total Blogs</th>
<td>{{total_blog}}</td>
</tr>
</table>
</div>
</div>

</html>
1 change: 1 addition & 0 deletions hackathon_starter/hackathon/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
url(r'^linkedin/$', views.linkedin, name='linkedin'),
url(r'^snippets/$', views.snippet_list, name='snippets'),
url(r'^twilio/$', views.twilio, name='twilio'),
url(r'^instagram/$', views.instagram, name='instagram'),
)
57 changes: 39 additions & 18 deletions hackathon_starter/hackathon/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
# Scripts
from scripts.steam import gamesPulling, steamIDPulling
from scripts.github import *
from scripts.tumblr import *
from scripts.tumblr import TumblrOauthClient
from scripts.twilioapi import *
from scripts.instagram import InstagramOauthClient

# Python
import oauth2 as oauth
Expand All @@ -29,6 +30,7 @@


getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)

def index(request):
context = {'hello': 'world'}
Expand All @@ -47,12 +49,14 @@ def twilio(request):
##################

def api_examples(request):
obtain_oauth_verifier = getTumblr.get_authorize_url()
#simpleoauthurl(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier}
instagram_url =getInstagram.get_authorize_url()
if not getTumblr.accessed:
obtain_oauth_verifier = getTumblr.authorize_url()
else:
obtain_oauth_verifier = '/hackathon/tumblr'
context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
return render(request, 'hackathon/api_examples.html', context)


#################
# STEAM API #
#################
Expand Down Expand Up @@ -113,19 +117,35 @@ def githubResume(request):
def tumblr(request):
''' Tumblr api calls '''
#retrieve verifier via url link
if not request.GET.items():
return HttpResponseRedirect('/hackathon/api/')
else:
getTumblr.get_access_token_url(request.GET.get('oauth_verifier'))
#get blogger twitterthecomic's blog information
blog = getTumblr.getBlogInfo('twitterthecomic')
#get tags that was tagged along starbucks
tagged_blog = getTumblr.getTaggedInfo("starbucks")
#get blog information tagged with starbucks
blogontag = getTumblr.getTaggedBlog("starbucks")
context = {'title': "What's up Starbucks?", 'blogData': blog, 'blogTag': tagged_blog, 'blogontag': blogontag}
return render(request, 'hackathon/tumblr.html', context)

#if not request.GET.items():
# return HttpResponseRedirect('/hackathon/api/')
if not getTumblr.accessed:
oauth_verifier = request.GET.get('oauth_verifier')
getTumblr.access_token_url(oauth_verifier)
#get blogger twitterthecomic's blog information
blog = getTumblr.getBlogInfo('twitterthecomic')
#get tags that was tagged along starbucks
tagged_blog = getTumblr.getTaggedInfo("starbucks")
#get blog information tagged with starbucks
blogontag = getTumblr.getTaggedBlog("starbucks")
#get user's information
userinfo, total_blog = getTumblr.getUserInfo()
context = {'title': "What's up Starbucks?", 'blogData': blog, 'blogTag': tagged_blog, 'blogontag': blogontag, 'userinfo': userinfo, 'total_blog':total_blog}
return render(request, 'hackathon/tumblr.html', context)


####################
# INSTAGRAM API #
####################

def instagram(request):
search_tag = 'kitten'
code = request.GET['code']
getInstagram.get_access_token(code)
#return tagged objects
tagged_media = getInstagram.get_tagged_media(search_tag)
context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': search_tag}
return render(request, 'hackathon/instagram.html', context)

##################
# LINKED IN API #
Expand Down Expand Up @@ -209,3 +229,4 @@ def user_login(request):
def user_logout(request):
logout(request)
return HttpResponseRedirect('/hackathon/')

2 changes: 2 additions & 0 deletions hackathon_starter/hackathon_starter/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,6 @@
TUMBLR_CONSUMER_SECRET ='lKWMtL2Lj8zr5pY51PVqT8ugeoG0DjrdgoFewM0QTSyJ12jP8d'
TWITTER_TOKEN = 'F05dgLAzHEOalb4K2xDQ8Umm8'
TWITTER_SECRET = 'Yy3a74Z7gvyhxRruJsvUtUl8uK8iv6qKkVqbZSijUxK71Z1qTY'
INSTAGRAM_CLIENT_ID = '77dc10b9e3624e908ce437c0a82da92e'
INSTAGRAM_CLIENT_SECRET = '8bcf3139857149aaba7acaa61288427f'

0 comments on commit 29174eb

Please sign in to comment.