Преглед изворни кода

Merged DrkSephy/django-hackathon-starter into default

Eswari Pravallika Swarna пре 10 година
родитељ
комит
0d810b52c4

+ 32 - 0
gulpfile.js

@@ -0,0 +1,32 @@
+// 1. Include gulp
+var gulp = require('gulp');
+
+// 2. Include any plugins you might need. 
+// NOTE: child_process is NOT a plugin but it is a requirement.
+var process = require('child_process');
+var install = require("gulp-install");
+
+// 3. Write out the tasks. 
+
+gulp.task('bowerinstall',function(){
+	console.info('Installing Bower Packages.')
+    gulp.src(['./bower.json', './package.json'])
+    .pipe(install());
+})
+
+gulp.task('djangomigrate', function(){
+	var spawn = process.spawn;
+	console.info('Doing Django Migrations');
+	var PIPE = {stdio: 'inherit'};
+	spawn('python',['./hackathon_starter/manage.py','migrate'],PIPE);
+});
+
+gulp.task('django', function(){
+	var spawn = process.spawn;
+	console.info('Starting Django server');
+	var PIPE = {stdio: 'inherit'};
+	spawn('python',['./hackathon_starter/manage.py','runserver'],PIPE);
+});
+
+// 4. Default Task
+gulp.task('default',['bowerinstall','django','djangomigrate']);

+ 4 - 1
hackathon_starter/hackathon/admin.py

@@ -2,8 +2,11 @@ from django.contrib import admin
 from hackathon.models import UserProfile, Profile, InstagramProfile, TwitterProfile
 
 # Register your models here.
+class TwitterProfileAdmin(admin.ModelAdmin):
+	list_display = ('user','twitter_user')
+
 admin.site.register(UserProfile)
 admin.site.register(Profile)
 admin.site.register(InstagramProfile)
-admin.site.register(TwitterProfile)
+admin.site.register(TwitterProfile, TwitterProfileAdmin)
 

+ 232 - 195
hackathon_starter/hackathon/scripts/instagram.py

@@ -1,4 +1,3 @@
-
 '''
 instagram.py contains a handful of methods for interacting
 with Instagram data and returning the responses as JSON.
@@ -12,200 +11,238 @@ import simplejson as json2
 import googlemaps
 from django.conf import settings
 from datetime import datetime
-from time import strftime
 
-authorization_url = 'https://api.instagram.com/oauth/authorize/?client_id='
-access_token_url = 'https://api.instagram.com/oauth/access_token'
+AUTHORIZATION_URL = 'https://api.instagram.com/oauth/authorize/?client_id='
+ACCESS_TOKEN_URL = 'https://api.instagram.com/oauth/access_token'
 
 class InstagramOauthClient(object):
-	'''
-	Python Client for Instagram API.
-	'''
-
-	access_token = None
-	user_data = None
-
-	def __init__(self, client_id, client_secret):
-		'''
-		Parameters:
-			client_id: String
-				- The client_id from registering application
-				  on Instagram.
-			client_secret: String
-				- The client_secret from registering application
-				  on Instagram.
-		'''
-
-		self.client_id 		= client_id
-		self.client_secret 	= client_secret
-
-
-	def get_authorize_url(self):
-		''' 
-		Obtains authorize url link with given client_id.
-
-		Returns:
-			auth_url: String
-				- 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.
-
-		Parameters:
-			code: String
-				- The code is retrieved from the authorization url parameter
-				  to obtain 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.user_data
-		#print self.access_token
-
-
-	def get_tagged_media(self, tag):
-		'''
-		Get recent tagged media.
-
-		Parameters:
-			tag: String
-				- The tag used to search the most recent media that's tagged with it.
-
-		Returns:
-			data: Dictionary
-				- A dictionary containing recent tagged 120 media counts data pertaining to each 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
-
-
-	def get_user_info(self, access_token):
-		'''
-		Get user information.
-
-		Parameters:
-			access_token: String
-				- The access_token given after granting permission
-				  application access to Instagram data.
-
-		Returns:
-			data: Dictionary
-				- A dictionary containing user information.
-		'''
-
-		user_info = 'https://api.instagram.com/v1/users/32833691/?access_token='+access_token
-		req = requests.get(user_info)
-		content = json2.loads(req.content)
-		data = content['data']
-		return data
-
-
-	def get_user_media(self, user_id, access_token):
-		'''
-		Parameters:
-			access_token: String
-				- The access_token given after granting permission
-				  application access to Instagram data.
-
-		Returns:
-			data: Dictionary
-				- A dictionary containing user media information.
-		'''
-
-		user_media = 'https://api.instagram.com/v1/users/'+str(user_id)+'/media/recent/?access_token='+access_token
-		#user_media = 'https://api.instagram.com/v1/users/32833691/media/recent/?access_token='+access_token
-		req = requests.get(user_media)
-		content = json2.loads(req.content)
-		data = content['data']
-		return data
-
-	def search_for_location(self, address, access_token):
-		'''
-		Parameters:
-			access_token: String
-				- The access_token given after granting permission
-				  application access to Instagram data.
-			address: String
-				- The address is a user input.
-
-		Returns:
-			location: Dictionary
-				- A dictionary returning the latitude, and longitude
-				  of an address.
-		'''		
-		gmaps = googlemaps.Client(key=settings.GOOGLEMAP_API_KEY)
-		#geocoding and address
-		geocode_result = gmaps.geocode(address)
-		
-		if geocode_result:
-			location = geocode_result[0]['geometry']['location']
-			return location
-
-
-	def search_location_ids(self, latitude, longitude, access_token):
-		search_location = 'https://api.instagram.com/v1/locations/search?lat='+str(latitude)+'&lng='+str(longitude)+'&access_token='+access_token+"&distance=5000"
-		req = requests.get(search_location)
-		data = json2.loads(req.content)
-		list_of_ids =[]
-		if data['meta']['code'] != 200:
-			raise Exception("Invalid response %s." % data['meta']['code'])
-		search_ids = data['data']
-		for data in search_ids:
-			for i in data:
-				if i == 'id':
-					list_of_ids.append(data[i])
-		return list_of_ids
-
-	def search_location_media(self, list_location_ids, access_token):
-		media = []
-		for location in list_location_ids:
-			media_by_location = 'https://api.instagram.com/v1/locations/'+location+'/media/recent?access_token='+access_token
-			req = requests.get(media_by_location)
-			content_all = json2.loads(req.content)
-			if content_all['pagination']:
-				temp_media=[]
-				next_url = content_all['pagination']['next_url']
-				req = requests.get(next_url)
-				content = json2.loads(req.content)
-				for i in content['data']:
-					i['created_time'] = datetime.fromtimestamp(int(i['created_time'])).strftime('%Y-%m-%d %H:%M:%S')
-					temp_media.append(i)
-				media += [temp_media]
-			else:
-				for i in content_all['data']:
-					for data in i:
-						if data == 'created_time':
-							i[data]= datetime.fromtimestamp(int(i[data])).strftime('%Y-%m-%d %H:%M:%S')
-				media.append(content_all['data'])
-		return media
-
-
-
+    '''
+    Python Client for Instagram API.
+    '''
+
+    access_token = None
+    user_data = None
+    is_authorized = False
+
+    def __init__(self, client_id, client_secret):
+        '''
+        Parameters:
+            client_id: String
+                - The client_id from registering application
+                  on Instagram.
+            client_secret: String
+                - The client_secret from registering application
+                  on Instagram.
+        '''
+        self.client_id = client_id
+        self.client_secret = client_secret
+
+
+    def get_authorize_url(self):
+        '''
+        Obtains authorize url link with given client_id.
+
+        Returns:
+            authURL: String
+                - The authorization url.
+        '''
+
+        redirectUri = '&redirect_uri=http://127.0.0.1:8000/hackathon/&response_type=code'
+        authURL = AUTHORIZATION_URL + self.client_id + redirectUri
+        #print authURL
+        return authURL
+
+    def get_access_token(self, code):
+        '''
+        Obtains access token.
+
+        Parameters:
+            code: String
+                - The code is retrieved from the authorization url parameter
+                  to obtain access_token.
+        '''
+
+        authSetting = {
+            'client_id' : self.client_id,
+            'client_secret' : self.client_secret,
+            'grant_type' : 'authorization_code',
+            'redirect_uri' : 'http://127.0.0.1:8000/hackathon/',
+            'code' : code}
+
+        authSettingUrl = urllib.urlencode(authSetting)
+        req = urllib2.Request(ACCESS_TOKEN_URL, authSettingUrl)
+        content = urllib2.urlopen(req)
+        jsonlist = json.load(content)
+        self.access_token = jsonlist['access_token']
+        self.user_data = jsonlist['user']
+        self.is_authorized = True
+
+
+
+
+
+
+
+def searchForLocation(address):
+    '''
+    Parameters:
+        address: String
+            - The address is a user input.
+
+    Returns:
+        location: Dictionary
+            - A dictionary returning the latitude, and longitude
+              of an address.
+    '''
+
+    gmaps = googlemaps.Client(key=settings.GOOGLEMAP_API_KEY)
+    #geocoding and address
+    geocodeResult = gmaps.geocode(address)
+
+    if geocodeResult:
+        location = geocodeResult[0]['geometry']['location']
+        return location
+
+
+def getTaggedMedia(tag, accessToken):
+    '''
+    Get recent tagged media.
+
+    Parameters:
+        tag: String
+            - The tag used to search the most recent media that's tagged with it.
+
+    Returns:
+        data: Dictionary
+            - A dictionary containing recent tagged 120 media
+              counts data pertaining to each media.
+    '''
+
+    tagUri = 'https://api.instagram.com/v1/tags/'
+    taggedMediaUrl = tagUri + tag + '/media/recent?access_token=' + accessToken
+    req = requests.get(taggedMediaUrl)
+    content = json2.loads(req.content)
+    data = content['data']
+
+    while len(data) <= 100:
+        nextUrl = content['pagination']['next_url']
+        req = requests.get(nextUrl)
+        content = json2.loads(req.content)
+        for i in content['data']:
+            data.append(i)
+    #print len(data)
+    return data
+
+
+def getUserInfo(accessToken):
+    '''
+    Get user information.
+
+    Parameters:
+        access_token: String
+            - The access_token given after granting permission
+              application access to Instagram data.
+
+    Returns:
+        data: Dictionary
+            - A dictionary containing user information.
+    '''
+
+    userInfo = 'https://api.instagram.com/v1/users/32833691/?access_token='+accessToken
+    req = requests.get(userInfo)
+    content = json2.loads(req.content)
+    data = content['data']
+    return data
+
+
+def getUserMedia(userId, accessToken):
+    '''
+    Parameters:
+        accessToken: String
+            - The access_token given after granting permission
+              application access to Instagram data.
+        userId: Integer
+            - User's instagram ID number.
+
+    Returns:
+        data: Dictionary
+            - A dictionary containing user media information.
+    '''
+
+    userMediaUri = 'https://api.instagram.com/v1/users/' + str(userId)
+    userMedia = userMediaUri + '/media/recent/?access_token=' + accessToken
+    req = requests.get(userMedia)
+    content = json2.loads(req.content)
+    data = content['data']
+    return data
+
+
+def searchLocationIds(lat, lng, accessToken):
+    '''
+    Parameters:
+        lat: Float
+            - The latitude of the input address
+        lng: Float
+            - The longitude of the input address
+
+    Returns:
+        listOfIds: Dictionary
+            - A dictionary returning the list of location ids
+              of the given address coordinates.
+    '''
+
+    locIdUri = 'https://api.instagram.com/v1/locations/search?lat=' + str(lat)
+    location = locIdUri+'&lng='+str(lng)+'&access_token='+ accessToken+'&distance=5000'
+    req = requests.get(location)
+    data = json2.loads(req.content)
+    listOfIds = []
+    if data['meta']['code'] != 200:
+        raise Exception("Invalid response %s." % data['meta']['code'])
+    searchIds = data['data']
+    for data in searchIds:
+        for i in data:
+            if i == 'id':
+                listOfIds.append(data[i])
+    return listOfIds
+
+
+def searchLocationMedia(listOfLocationIds, accessToken):
+    '''
+    Parameters:
+        listOfLocationIds: Float
+            - list of location ids retrieve from coordinate of
+              of searched address.
+        access_token: String
+            - The access_token given after granting permission
+              application access to Instagram data.
+
+    Returns:
+        media: Dictionary
+            - A dictionary returning the list of recent media
+              of the list of location ids.
+    '''
+
+    media = []
+    locationUri = 'https://api.instagram.com/v1/locations/'
+    for location in listOfLocationIds:
+        mediaByLocation = locationUri+location+'/media/recent?access_token='+ accessToken
+        req = requests.get(mediaByLocation)
+        contentAll = json2.loads(req.content)
+        if contentAll['pagination']:
+            tempMedia = []
+            nextUrl = contentAll['pagination']['next_url']
+            req = requests.get(nextUrl)
+            content = json2.loads(req.content)
+            for i in content['data']:
+                i['created_time'] = datetime.fromtimestamp(int(i['created_time']))
+                i['created_time'] = i['created_time'].strftime('%Y-%m-%d %H:%M:%S')
+                tempMedia.append(i)
+            media += [tempMedia]
+        else:
+            for i in contentAll['data']:
+                for data in i:
+                    if data == 'created_time':
+                        i[data] = datetime.fromtimestamp(int(i[data]))
+                        i[data] = i[data].strftime('%Y-%m-%d %H:%M:%S')
+            media.append(contentAll['data'])
+    return media

+ 21 - 0
hackathon_starter/hackathon/scripts/nytimes.py

@@ -0,0 +1,21 @@
+'''module containing a handful of methods for aggregating
+data from the NY Times.'''
+
+import requests
+import json
+
+def fetcharticle(apikey, url):
+    '''returns the JSON data of the most
+    popular articles by view from the past 24 hours.'''
+    parameters = {'api-key' : apikey}
+    req = requests.get(url, params=parameters)
+    data = json.loads(req.content)
+    parsedData = []
+    for datum in data['results']:
+        new_data = {"title": datum["title"],
+                "abstract": datum["abstract"],
+                "section": datum["section"],
+                "byline": datum["byline"],
+                }
+        parsedData.append(new_data)
+    return parsedData

+ 177 - 156
hackathon_starter/hackathon/scripts/twitter.py

@@ -11,227 +11,248 @@ import requests
 import base64, random
 import urllib
 import binascii
-import time, collections, json, hmac, hashlib
+import time, collections, hmac, hashlib
 import simplejson as json2
 
-request_token_url = 'https://api.twitter.com/oauth/request_token'
-access_token_url = 'https://api.twitter.com/oauth/access_token'
-authorize_url = 'https://api.twitter.com/oauth/authorize'
+REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
+ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
+AUTHORIZE_URL = 'https://api.twitter.com/oauth/authorize'
 
 class TwitterOauthClient(object):
-	'''
-	Python Client for Twitter API.
-	'''	
-
-	oauth_token = None
-	oauth_token_secret = None
-
-
-	def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
-		'''
-		Parameters:
-			consumer_key: String
-				- The consumer_key from registering application
-				  on Instagram.
-			consumer_secret: String
-				- The consumer_secret from registering application
-				  on Instagram.
-		'''		
-		self.consumer_key = consumer_key
-		self.consumer_secret = consumer_secret
-		self.access_token = access_token
-		self.access_token_secret = access_token_secret
-		self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
-		
-
-	def get_authorize_url(self):
-		'''
-		Obtained oauth_token and oauth_token_secret from request_token_url,
-		returns an authorize url. 
-
-		From the redirect url, we obtain the oauth verifier.
-		'''
-
-		client = oauth.Client(self.consumer)
-		resp, content = client.request(request_token_url, 'GET')
-
-		if int(resp['status']) != 200:
-			raise Exception('Invalid response %s' %resp['status'])
-
-		request_token = dict(urlparse.parse_qsl(content))
-
-		#temporary
-		self.oauth_token = request_token['oauth_token']
-		self.oauth_token_secret  = request_token['oauth_token_secret']
-		print self.oauth_token
-
-		#link to authorize app access twitter data and return to twitter api example page
-		link = authorize_url+"?oauth_token="+self.oauth_token+"&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/twitter/"
-		return link
+    '''
+    Python Client for Twitter API.
+    '''
+
+    oauth_token = None
+    oauth_token_secret = None
+    username = None
+    is_authorized = False
+
+
+    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
+        '''
+        Parameters:
+            consumer_key: String
+                - The consumer_key from registering application
+                  on Instagram.
+            consumer_secret: String
+                - The consumer_secret from registering application
+                  on Instagram.
+        '''
+
+        self.consumer_key = consumer_key
+        self.consumer_secret = consumer_secret
+        self.access_token = access_token
+        self.access_token_secret = access_token_secret
+        self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
+
+
+    def get_authorize_url(self):
+        '''
+        Obtained oauth_token and oauth_token_secret from request_token_url,
+        returns an authorize url.
+
+        From the redirect url, we obtain the oauth verifier.
+
+        Returns:
+            authURL: String
+                - The authorization url.
+        '''
+
+        client = oauth.Client(self.consumer)
+        resp, content = client.request(REQUEST_TOKEN_URL, 'GET')
+
+        if int(resp['status']) != 200:
+            raise Exception('Invalid response %s' %resp['status'])
+
+        requestToken = dict(urlparse.parse_qsl(content))
+
+        #temporary
+        self.oauth_token = requestToken['oauth_token']
+        self.oauth_token_secret = requestToken['oauth_token_secret']
+        #print self.oauth_token
+
+        #link to authorize app access twitter data and return to twitter api example page
+        redirectUri = '&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/twitter/'
+        authURL = AUTHORIZE_URL+"?oauth_token="+self.oauth_token+redirectUri
+        return authURL
+
 
-	def get_access_token_url(self, oauth_verifier):
-		
-		token = oauth.Token(self.oauth_token, self.oauth_token_secret)
-		token.set_verifier(oauth_verifier)
+    def get_access_token_url(self, oauthVerifier):
+        '''
+        Get access token from redirect url.
 
-		client = oauth.Client(self.consumer, token)
-		resp, content = client.request(access_token_url, 'POST')
-		
-		if int(resp['status']) != 200:
-			raise Exception('Invalid response %s' %resp['status'])
+        Parameters:
+            oauthVerifier: String
+                - A paramater retrieved from scraping the redirect url.
 
-		print content
-		access_token = dict(urlparse.parse_qsl(content))
+        Returns:
+            data: Dictionary
+                - A dictionary containing recent tagged 120 media
+                  counts data pertaining to each media.
+        '''
 
-		#permanent
-		self.oauth_token = access_token['oauth_token']
-		self.oauth_token_secret = access_token['oauth_token_secret']
-		self.user_id = access_token['user_id']
-		self.username = access_token['screen_name']
+        token = oauth.Token(self.oauth_token, self.oauth_token_secret)
+        token.set_verifier(oauthVerifier)
 
+        client = oauth.Client(self.consumer, token)
+        resp, content = client.request(ACCESS_TOKEN_URL, 'POST')
 
+        if int(resp['status']) != 200:
+            raise Exception('Invalid response %s' %resp['status'])
 
+        #print content
+        accessToken = dict(urlparse.parse_qsl(content))
 
-	def get_trends_available(self, yahoo_consumer_key):
-		method = "get"
-		link = 'https://api.twitter.com/1.1/trends/available.json'
-		link_parameters = {}
-		#link = 'https://api.twitter.com/1.1/trends/closest.json'
-		#link_parameters = {'lat':'40.782032', 'long':'-73.9717188'}
-		#link = 'https://api.twitter.com/1.1/trends/place.json'
-		#link_parameters = {'id': '1'}
-		
+        #permanent
+        self.oauth_token = accessToken['oauth_token']
+        self.oauth_token_secret = accessToken['oauth_token_secret']
+        self.username = accessToken['screen_name']
+        self.is_authorized = True
 
-		oauth_parameters = get_oauth_parameters(
-		    self.consumer_key,
-		    self.access_token
-		)
 
-		oauth_parameters['oauth_signature'] = generate_signature(
-		    method,
-		    link,
-		    link_parameters,
-		    oauth_parameters,
-		    self.consumer_key,
-		    self.consumer_secret,
-		    self.access_token_secret
-		)
+    def get_trends_available(self, yahooConsumerKey):
+        '''
+        Get the locations that Twitter has trending topic information for.
 
-		headers = {'Authorization': create_auth_header(oauth_parameters)}
+        '''
 
-		if link_parameters:
-			link += '?'+urllib.urlencode(link_parameters)
+        method = "get"
+        link = 'https://api.twitter.com/1.1/trends/available.json'
+        linkParameters = {}
+        #link = 'https://api.twitter.com/1.1/trends/closest.json'
+        #link_parameters = {'lat':'40.782032', 'long':'-73.9717188'}
+        #link = 'https://api.twitter.com/1.1/trends/place.json'
+        #link_parameters = {'id': '1'}
 
-		req = requests.get(link, headers=headers)
-		#print req.status_code
-		
-		if int(req.status_code) != 200:
-			raise Exception('Invalid response %s' %req.status_code)
-
-		content = json2.loads(req.content)
-		#print len(content)
-		
-		for place in content:
-			for e in place:
-				if e == 'url':
-					request_neighbor_data=  requests.get(place[e]+'/neighbors?appid='+yahoo_consumer_key+'&format=json')
-					#print request_neighbor_data.status_code
-					if request_neighbor_data.status_code == 200:
-						neighbor = json2.loads(request_neighbor_data.content)
-					else:
-						neighbor = {}
+        oauthParameters = getOauthParameters(
+            self.consumer_key,
+            self.access_token
+        )
 
-			place['neighbor'] = neighbor
-					#print place
+        oauthParameters['oauth_signature'] = generateSignature(
+            method,
+            link,
+            linkParameters,
+            oauthParameters,
+            self.consumer_secret,
+            self.access_token_secret
+        )
 
+        headers = {'Authorization': createAuthHeader(oauthParameters)}
 
-		return content
-		
+        if linkParameters:
+            link += '?'+urllib.urlencode(linkParameters)
 
+        req = requests.get(link, headers=headers)
+        #print req.status_code
 
+        if int(req.status_code) != 200:
+            raise Exception('Invalid response %s' %req.status_code)
 
+        content = json2.loads(req.content)
+        #print len(content)
 
-def percent_encode(string):
-	'''
-	Percent encode strings.
-	'''
-	return urllib.quote(string, safe='~')
+        for place in content:
+            for item in place:
+                if item == 'url':
+                    url = place[item]+'/neighbors?appid='+yahooConsumerKey+'&format=json'
+                    requestNeighborData = requests.get(url)
+                    #print request_neighbor_data.status_code
+                    if requestNeighborData.status_code == 200:
+                        neighbor = json2.loads(requestNeighborData.content)
+                    else:
+                        neighbor = {}
 
+            place['neighbor'] = neighbor
+                    #print place
 
-def get_nonce():
-	'''
-	Generate unique token per request.
-	'''
 
-	n = base64.b64encode(''.join([str(random.randint(0, 9)) for i in range(24)]))
-	return n
+        return content
 
 
-def generate_signature(method, link, link_parameters, oauth_parameters, oauth_consumer_key, oauth_consumer_secret, oauth_token_secret=None, status=None):
+
+def percentEncode(string):
+    '''
+    Percent encode strings.
+    '''
+    return urllib.quote(string, safe='~')
+
+
+def getNonce():
+    '''
+    Generate unique token per request.
+    '''
+
+    nonce = base64.b64encode(''.join([str(random.randint(0, 9)) for i in range(24)]))
+    return nonce
+
+
+def generateSignature(method, link, linkParameters, oauthParameters,
+                      oauthConsumerSecret, oauthTokenSecret=None):
     '''
     Generate signature.
     '''
-    if link_parameters:
-    	new_dict = dict(oauth_parameters, **link_parameters)
-    	parameters = urllib.urlencode(collections.OrderedDict(sorted(new_dict.items())))
+
+    if linkParameters:
+        newDict = dict(oauthParameters, **linkParameters)
+        params = urllib.urlencode(collections.OrderedDict(sorted(newDict.items())))
     else:
-    	parameters = urllib.urlencode(collections.OrderedDict(sorted(oauth_parameters.items())))
+        params = urllib.urlencode(collections.OrderedDict(sorted(oauthParameters.items())))
 
     #Create your Signature Base String
-    signature_base_string = ( method.upper() + '&' + percent_encode(str(link)) + '&' + percent_encode(parameters))
+    signatureBaseString = (method.upper()+'&'+percentEncode(str(link))+'&'+percentEncode(params))
 
     #Get the signing key
-    signing_key = create_signing_key(oauth_consumer_secret, oauth_token_secret)
+    signingKey = createSigningKey(oauthConsumerSecret, oauthTokenSecret)
 
-    return calculate_signature(signing_key, signature_base_string)
+    return calculateSignature(signingKey, signatureBaseString)
 
 
 
-def calculate_signature(signing_key, signature_base_string):
+def calculateSignature(signingKey, signatureBaseString):
     '''
     Calculate signature using HMAC-SHA1 hashing algorithm.
     '''
-    hashed = hmac.new(signing_key, signature_base_string, hashlib.sha1)
+    hashed = hmac.new(signingKey, signatureBaseString, hashlib.sha1)
 
     sig = binascii.b2a_base64(hashed.digest())[:-1]
 
-    return percent_encode(sig)
+    return percentEncode(sig)
 
 
-def create_signing_key(oauth_consumer_secret, oauth_token_secret):
+def createSigningKey(oauthConsumerSecret, oauthTokenSecret):
     '''
     Creates a key to sign the request with.
     '''
 
-    signing_key = percent_encode(oauth_consumer_secret) + '&' + percent_encode(oauth_token_secret)
+    signingKey = percentEncode(oauthConsumerSecret) + '&' + percentEncode(oauthTokenSecret)
 
-    return signing_key
+    return signingKey
 
 
-def create_auth_header(parameters):
-	'''
-	Format authorization header with oath parameters.
-	'''
+def createAuthHeader(parameters):
+    '''
+    Format authorization header with oath parameters.
+    '''
 
-	ordered_parameters = collections.OrderedDict(sorted(parameters.items()))
-	auth_header = ('%s="%s"' % (k, v) for k, v in ordered_parameters.iteritems())
+    orderedParameters = collections.OrderedDict(sorted(parameters.items()))
+    authHeader = ('%s="%s"' % (k, v) for k, v in orderedParameters.iteritems())
 
-	return "OAuth " + ', '.join(auth_header)
+    return "OAuth " + ', '.join(authHeader)
 
 
-def get_oauth_parameters(consumer_key, access_token):
+def getOauthParameters(consumerKey, accessToken):
     '''
     Returns parameters for making requests.
     '''
-    oauth_parameters = {
+    oauthParameters = {
         'oauth_timestamp': str(int(time.time())),
         'oauth_signature_method': "HMAC-SHA1",
         'oauth_version': "1.0",
-        'oauth_token': access_token,
-        'oauth_nonce': get_nonce(),
-        'oauth_consumer_key': consumer_key
+        'oauth_token': accessToken,
+        'oauth_nonce': getNonce(),
+        'oauth_consumer_key': consumerKey
     }
 
-    return oauth_parameters
-
-    
+    return oauthParameters

+ 2 - 2
hackathon_starter/hackathon/templates/hackathon/api_examples.html

@@ -11,8 +11,8 @@
 			<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 class="col-sm-4"><a href="{{twitter_url}}">Twitter Example</a></div>
+		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/instagram/">Instagram Example</a></div>
+		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twitter/">Twitter Example</a></div>
 		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/quandlstocks/">Quandl Example</a></div>
 
   	</div>

+ 61 - 0
hackathon_starter/hackathon/templates/hackathon/nytimes.html

@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<html>
+<body>
+	{% include 'hackathon/base.html' %}
+
+    <h1 class="text-center"> New York Times Collection </h1>
+    <h2 class="text-center"> Popular Stories Data </h2>
+	<div class="col-lg-12">
+        <div class="table-responsive">
+            <table class="table table-bordered table-hover table-striped tablesorter">
+                <thead>
+                <tr>
+                <th class="header"> Title <i class="icon-sort"></i></th>
+                <th class="header"> Abstract <i class="icon-sort"></i></th>
+                <th class="header"> Section Located <i class="icon-sort"></i></th>
+                <th class="header"> Author <i class="icon-sort"></i></th>  
+                </tr>
+            </thead>
+            <tbody>
+
+            {% for data in everyData.pop %}
+                <tr>
+                    <td>{{ data.title }}</td>
+                    <td>{{ data.abstract }}</td>
+                    <td>{{ data.section }}</td>
+                    <td>{{ data.byline }}</td>
+                </tr>
+            {% endfor %}
+            </tbody>
+            </table>
+        </div>
+    </div>
+    <h2 class="text-center"> Top Stories Data </h2>
+    <div class="col-lg-12">
+        <div class="table-responsive">
+            <table class="table table-bordered table-hover table-striped tablesorter">
+                <thead>
+                <tr>
+                <th class="header"> Title <i class="icon-sort"></i></th>
+                <th class="header"> Abstract <i class="icon-sort"></i></th>
+                <th class="header"> Section Located <i class="icon-sort"></i></th>
+                <th class="header"> Author <i class="icon-sort"></i></th>  
+                </tr>
+            </thead>
+            <tbody>
+
+            {% for data in everyData.top %}
+                <tr>
+                    <td>{{ data.title }}</td>
+                    <td>{{ data.abstract }}</td>
+                    <td>{{ data.section }}</td>
+                    <td>{{ data.byline }}</td>
+                </tr>
+            {% endfor %}
+            </tbody>
+            </table>
+        </div>
+    </div>
+  
+</body>
+</html>

+ 2 - 2
hackathon_starter/hackathon/templates/hackathon/quandl.html

@@ -30,7 +30,7 @@
             </table>
         </div>
     </div>
-
+    <h2 class="text-center"> SnP 500 Data </h2>
     <div class="col-lg-12">
         <div class="table-responsive">
             <table class="table table-bordered table-hover table-striped tablesorter">
@@ -56,7 +56,7 @@
             </table>
         </div>
     </div>
-
+    <h2 class="text-center"> Nasdaq Data </h2>
     <div class="col-lg-12">
         <div class="table-responsive">
             <table class="table table-bordered table-hover table-striped tablesorter">

+ 4 - 0
hackathon_starter/hackathon/tests.py

@@ -70,3 +70,7 @@ class HackathonViewsTestCase(TestCase):
 	def testTwilio(self):
 		resp = self.client.get('/hackathon/twilio/')
 		self.assertEqual(resp.status_code, 200)
+	
+	def testNytimespop(self):
+		resp = self.client.get('/hackathon/nytimespop/')
+		self.assertEqual(resp.status_code, 200)

+ 3 - 0
hackathon_starter/hackathon/urls.py

@@ -30,4 +30,7 @@ urlpatterns = patterns('',
     url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
     url(r'^quandlDowJones/$', views.quandlDowJones, name='quandldowjones'),
     url(r'^quandlstocks/$', views.quandlstocks, name='quandlstocks'),
+    url(r'^nytimespop/$', views.nytimespop, name='nytimespop'),
+    url(r'^nytimestop/$', views.nytimestop, name='nytimestop'),
+    url(r'^nytimesarticles/$', views.nytimesarticles, name='nytimesarticles'),
 )

+ 109 - 75
hackathon_starter/hackathon/views.py

@@ -16,10 +16,11 @@ from scripts.steam import gamespulling, steamidpulling
 from scripts.github import *
 from scripts.tumblr import TumblrOauthClient
 from scripts.twilioapi import *
-from scripts.instagram import InstagramOauthClient
+from scripts.instagram import *
 from scripts.scraper import steamDiscounts
 from scripts.quandl import *
 from scripts.twitter import TwitterOauthClient
+from scripts.nytimes import *
 
 # Python
 import oauth2 as oauth
@@ -32,12 +33,66 @@ from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
 
-
 getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
 getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)
 getTwitter = TwitterOauthClient(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
 
 def index(request):
+    print "index: " + str(request.user)
+
+    if not request.user.is_active:
+        if request.GET.items():
+            if 'oauth_verifier' in request.GET.keys():
+                oauth_verifier = request.GET['oauth_verifier']
+                getTwitter.get_access_token_url(oauth_verifier) 
+
+                try:
+                    user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
+                except User.DoesNotExist:
+                    username = getTwitter.username + '_twitter'
+                    new_user = User.objects.create_user(username, username+'@madewithtwitter.com', 'password')
+                    new_user.save()
+                    profile = TwitterProfile(user = new_user,oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
+                    profile.save()
+                user = authenticate(username=getTwitter.username+'_twitter', password='password')
+                login(request, user)
+            elif 'code' in request.GET.keys():
+                code = request.GET['code']
+                getInstagram.get_access_token(code)
+
+                try: 
+                    user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
+                except User.DoesNotExist:
+                    username = getInstagram.user_data['username']+'_instagram'
+                    new_user = User.objects.create_user(username, username+'@madewithinstagram.com', 'password')
+                    new_user.save()
+                    profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
+                    profile.save()
+                user = authenticate(username=getInstagram.user_data['username']+'_instagram' , password='password')
+                login(request, user)
+    else:
+        if request.GET.items():
+            if 'oauth_verifier' in request.GET.keys():
+                oauth_verifier = request.GET['oauth_verifier']
+                getTwitter.get_access_token_url(oauth_verifier)
+                user = User.objects.get(username = request.user.username)
+
+                try:
+                    twitterUser = TwitterProfile.objects.get(user = user.id)
+                except TwitterProfile.DoesNotExist:
+                    profile = TwitterProfile(user = user, oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
+                    profile.save()
+            elif 'code' in request.GET.keys():
+                code = request.GET['code']
+                getInstagram.get_access_token(code)
+                user = User.objects.get(username = request.user.username)
+
+                try: 
+                    instagramUser = InstagramProfile.objects.get(user= user.id)
+                except InstagramProfile.DoesNotExist:
+                    profile = InstagramProfile(user = user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
+                    profile.save()
+
     context = {'hello': 'world'}
     return render(request, 'hackathon/index.html', context)
 
@@ -48,13 +103,12 @@ def index(request):
 
 def api_examples(request):
     instagram_url =getInstagram.get_authorize_url()
-    twitter_url = getTwitter.get_authorize_url()
     if not getTumblr.accessed:
         obtain_oauth_verifier = getTumblr.authorize_url()
     else:
         obtain_oauth_verifier = '/hackathon/tumblr'
     #obtain_oauth_verifier = getTumblr.authorize_url()
-    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url, 'twitter_url':twitter_url}
+    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
     return render(request, 'hackathon/api_examples.html', context)
 
 #################
@@ -117,6 +171,32 @@ def quandlstocks(request):
     return render(request, 'hackathon/quandl.html', { 'everyData': everyData })
 
 #################
+#  NYTIMES API  #
+#################
+
+def nytimespop(request):
+    '''Returns JSON response about the most viewed articles for the last 24 hours.'''
+    POPAPIKEY = 'be4cd251d8a4f1a3362689088bdb0255:0:71947444'
+    popdata = fetcharticle(POPAPIKEY, 'http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?')
+    return JSONResponse({'data': popdata})
+
+def nytimestop(request):
+    '''Returns JSON response about the articles located in the homepage'''
+    TOPAPIKEY = 'c9655598e1fd4ff591f6d46f2321260e:17:71947444'
+    topdata = fetcharticle(TOPAPIKEY, 'http://api.nytimes.com/svc/topstories/v1/home.json?')
+    return JSONResponse({'data': topdata})
+
+def nytimesarticles(request):
+    POPAPIKEY = 'be4cd251d8a4f1a3362689088bdb0255:0:71947444'
+    TOPAPIKEY = 'c9655598e1fd4ff591f6d46f2321260e:17:71947444'
+    everyData = {}
+    popdata = fetcharticle(POPAPIKEY, 'http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?')
+    topdata = topdata = fetcharticle(TOPAPIKEY, 'http://api.nytimes.com/svc/topstories/v1/home.json?')
+    everyData['top'] = topdata
+    everyData['pop'] = popdata
+    return render(request, 'hackathon/nytimes.html', { 'everyData': everyData })
+
+#################
 #   GITHUB API  #
 #################
 
@@ -200,54 +280,32 @@ def tumblr(request):
 ####################
 
 def instagram(request):
-    code = request.GET['code']
-    getInstagram.get_access_token(code)
-
-    #check if user in User profile
-    if not User.objects.all().filter(username=request.user.username):
-        print "anno"
-        try:  
-            user = User.objects.get(username=getInstagram.user_data['username'])
-        except User.DoesNotExist:
-            username = getTwitter.username 
-            new_user = User.objects.create_user(username, username+'@madewithinstagram.com', 'password')
-            new_user.save()
-            profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=new_user.username+'instagram')
-            profile.save()
-        user = authenticate(username=getInstagram.user_data['username'] , password='password')
-        login(request, user)            
-    else:
-        print "exist instagram"
-        #check if user has an Instragram profile
-        try:  
-            user = User.objects.get(username=request.user.username)
-            twitterUser = InstagramProfile.objects.get(user=user.id)
-        except InstagramProfile.DoesNotExist:
-            new_user = User.objects.get(username=request.user.username)
-            profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=new_user.username+'@instagram')
-            profile.save()  
-
-
-    search_tag = 'kitten'
-    #return tagged objects
-    tagged_media = getInstagram.get_tagged_media(search_tag)
+    #print getInstagram.is_authorized
 
+    if getInstagram.is_authorized:
+        search_tag = 'kitten'
+        #return tagged objects
+        instagramUser = InstagramProfile.objects.get(user=request.user)
+        tagged_media = getTaggedMedia(search_tag, instagramUser.access_token)        
+    else:
+        instagram_url =getInstagram.get_authorize_url()
+        return HttpResponseRedirect(instagram_url)
+    
     context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': search_tag}
     return render(request, 'hackathon/instagram.html', context)
 
 def instagramUser(request):
     ''' Returns JSON response about a specific Instagram User. '''
 
-    user_id = User.objects.get(username='mk200789').id
-    access_token = Profile.objects.get(user=user_id).oauth_secret
-    parsedData = getInstagram.get_user_info(access_token)
+    access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
+    parsedData = getUserInfo(access_token)
     return JsonResponse({ 'data': parsedData })
 
 def instagramUserMedia(request):
     ''' Returns JSON response about a specific Instagram User's Media. '''
-    user_id = User.objects.get(username='mk200789').id
-    access_token = Profile.objects.get(user=user_id).oauth_secret
-    parsedData = getInstagram.get_user_media(32833691,access_token)
+
+    access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
+    parsedData = getUserMedia(32833691, access_token)
     return JsonResponse({'data': parsedData })
 
 def instagramMediaByLocation(request):
@@ -261,12 +319,11 @@ def instagramMediaByLocation(request):
                 #if user has an Instagram profile, query the search
                 if InstagramProfile.objects.all().filter(user=user.id):
                     address = request.GET.get('address_field')
-                    instagramUser = InstagramProfile.objects.get(user=user.id)
-                    access_token = instagramUser.access_token
-                    geocode_result = getInstagram.search_for_location(address, access_token)
+                    access_token = InstagramProfile.objects.get(user=user.id).access_token
+                    geocode_result = searchForLocation(address)
                     if geocode_result:
-                        location_ids =getInstagram.search_location_ids(geocode_result['lat'], geocode_result['lng'], access_token)
-                        media = getInstagram.search_location_media(location_ids, access_token)
+                        location_ids = searchLocationIds(geocode_result['lat'], geocode_result['lng'], access_token)
+                        media = searchLocationMedia(location_ids, access_token)
                         title = address
                         err_msg = ''
                 else:
@@ -282,36 +339,13 @@ def instagramMediaByLocation(request):
 ####################
 #   TWITTER API    #
 ####################
-def twitter(request):
-    oauth_verifier = request.GET['oauth_verifier']
-    getTwitter.get_access_token_url(oauth_verifier)   
-    print request.user
 
-    if not User.objects.all().filter(username=request.user.username):
-        try:  
-            user = User.objects.get(username=getTwitter.username)
-        except User.DoesNotExist:
-            username = getTwitter.username 
-            new_user = User.objects.create_user(username, username+'@madewithtwitter.com', 'password')
-            new_user.save()
-            profile = TwitterProfile(user = new_user,oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=new_user.username+'twitter')
-            profile.save()
-        user = authenticate(username=getTwitter.username, password='password')
-        login(request, user)            
+def twitter(request):
+    if getTwitter.is_authorized:
+        value = getTwitter.get_trends_available(settings.YAHOO_CONSUMER_KEY)
     else:
-        print "exist twitter"
-        #check if user has an Instragram profile
-        try:  
-            user = User.objects.get(username=request.user.username)
-            twitterUser = TwitterProfile.objects.get(user=user.id)
-        except TwitterProfile.DoesNotExist:
-            new_user = User.objects.get(username=request.user.username)
-            profile = TwitterProfile(user = new_user, oauth_token = getTwitter.oauth_token, oauth_token_secret = getTwitter.oauth_token_secret, twitter_user=new_user.username+'@twitter')
-            profile.save()            
-
-
-    value = getTwitter.get_trends_available(settings.YAHOO_CONSUMER_KEY)
-    #yahoo_woeid_link = 'http://where.yahooapis.com/v1/place/'+returned_woeid+'?appid='+settings.YAHOO_CONSUMER_KEY
+        tumblr_url = getTwitter.get_authorize_url()
+        return HttpResponseRedirect(tumblr_url)
 
     context ={'title': 'twitter', 'value': value}
     return render(request, 'hackathon/twitter.html', context)
@@ -424,5 +458,5 @@ def tumblr_login(request):
     return HttpResponseRedirect(tumblr_url)
 
 def twitter_login(request):
-    twitter_url = getTwitter.get_authorize_url()
+    twitter_url = getTwitter.get_authorize_url()     
     return HttpResponseRedirect(twitter_url)