Skip to content

Commit

Permalink
python3 compat changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon Heaton committed Oct 23, 2014
1 parent dee95d8 commit 82e65c7
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 70 deletions.
22 changes: 15 additions & 7 deletions get_access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@
except Exception:
pass

client_id = raw_input("Client ID: ").strip()
client_secret = raw_input("Client Secret: ").strip()
redirect_uri = raw_input("Redirect URI: ").strip()
raw_scope = raw_input("Requested scope (separated by spaces, blank for just basic read): ").strip()
# Fix Python 2.x.
try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass

client_id = input("Client ID: ").strip()
client_secret = input("Client Secret: ").strip()
redirect_uri = input("Redirect URI: ").strip()
raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip()
scope = raw_scope.split(' ')
# For basic, API seems to need to be set explicitly
if not scope or scope == [""]:
Expand All @@ -26,10 +33,11 @@
api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
redirect_uri = api.get_authorize_login_url(scope = scope)

print "Visit this page and authorize access in your browser:\n", redirect_uri
print ("Visit this page and authorize access in your browser: "+ redirect_uri)

code = raw_input("Paste in code in query string after redirect: ").strip()
code = (str(input("Paste in code in query string after redirect: ").strip()))

access_token = api.exchange_code_for_access_token(code)
print "access token:\n", access_token
print ("access token: " )
print (access_token)

6 changes: 1 addition & 5 deletions instagram/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,19 @@ def _do_api_request(self, url, method="GET", body=None, headers=None):
ips = self.api.client_ips
signature = hmac.new(secret, ips, sha256).hexdigest()
headers['X-Insta-Forwarded-For'] = '|'.join([ips, signature])

response, content = OAuth2Request(self.api).make_request(url, method=method, body=body, headers=headers)
if response['status'] == '503' or response['status'] == '429':
raise InstagramAPIError(response['status'], "Rate limited", "Your client is making too many request per second")

try:
content_obj = simplejson.loads(content)
content_obj = simplejson.loads(content.decode())
except ValueError:
raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status'])

# Handle OAuthRateLimitExceeded from Instagram's Nginx which uses different format to documented api responses
if 'meta' not in content_obj:
if content_obj.get('code') == 420 or content_obj.get('code') == 429:
error_message = content_obj.get('error_message') or "Your client is making too many request per second"
raise InstagramAPIError(content_obj.get('code'), "Rate limited", error_message)
raise InstagramAPIError(content_obj.get('code'), content_obj.get('error_type'), content_obj.get('error_message'))

api_responses = []
status_code = content_obj['meta']['code']
self.api.x_ratelimit_remaining = response.get("x-ratelimit-remaining",None)
Expand Down
2 changes: 1 addition & 1 deletion instagram/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def exchange_for_access_token(self, code=None, username=None, password=None, sco
http_object = Http(disable_ssl_certificate_validation=True)
url = self.api.access_token_url
response, content = http_object.request(url, method="POST", body=data)
parsed_content = simplejson.loads(content)
parsed_content = simplejson.loads(content.decode())
if int(response['status']) != 200:
raise OAuth2AuthExchangeError(parsed_content.get("error_message", ""))
return parsed_content['access_token'], parsed_content['user']
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
bottle==0.12.7
bottle-session==0.3
httplib2==0.9
python-instagram==1.1.3
redis==2.10.3
simplejson==3.6.3
wsgiref==0.1.2
beaker==1.6.4
120 changes: 64 additions & 56 deletions sample_app.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import bottle_session
import bottle
from bottle import route, redirect, post, run, request
import beaker.middleware
from bottle import route, redirect, post, run, request, hook
from instagram import client, subscriptions

bottle.debug(True)

app = bottle.app()
plugin = bottle_session.SessionPlugin(cookie_lifetime=600)
app.install(plugin)
session_opts = {
'session.type': 'file',
'session.data_dir': './session/',
'session.auto': True,
}

app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)

CONFIG = {
'client_id': '<client_id>',
Expand All @@ -17,8 +21,12 @@

unauthenticated_api = client.InstagramAPI(**CONFIG)

@hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']

def process_tag_update(update):
print update
print(update)

reactor = subscriptions.SubscriptionsReactor()
reactor.register_callback(subscriptions.SubscriptionType.TAG, process_tag_update)
Expand All @@ -28,8 +36,8 @@ def home():
try:
url = unauthenticated_api.get_authorize_url(scope=["likes","comments"])
return '<a href="%s">Connect with Instagram</a>' % url
except Exception, e:
print e
except Exception as e:
print(e)

def get_nav():
nav_menu = ("<h1>Python Instagram</h1>"
Expand All @@ -48,25 +56,25 @@ def get_nav():
return nav_menu

@route('/oauth_callback')
def on_callback(session):
def on_callback():
code = request.GET.get("code")
if not code:
return 'Missing code'
try:
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
print "access token= " + access_token
if not access_token:
return 'Could not get access token'
api = client.InstagramAPI(access_token=access_token)
session['access_token']=access_token
except Exception, e:
print e
request.session['access_token'] = access_token
print ("access token="+access_token)
except Exception as e:
print(e)
return get_nav()

@route('/recent')
def on_recent(session):
access_token = session.get('access_token')
def on_recent():
content = "<h2>User Recent Media</h2>"
access_token = request.session['access_token']
if not access_token:
return 'Missing Access Token'
try:
Expand All @@ -79,30 +87,30 @@ def on_recent(session):
photos.append('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url()))
else:
photos.append('<img src="%s"/>' % (media.get_low_resolution_url()))
print media
print(media)
photos.append("<br/> <a href='/media_like/%s'>Like</a> <a href='/media_unlike/%s'>Un-Like</a> LikesCount=%s</div>" % (media.id,media.id,media.like_count))
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/media_like/<id>')
def media_like(session,id):
access_token = session.get('access_token')
def media_like(id):
access_token = request.session['access_token']
api = client.InstagramAPI(access_token=access_token)
api.like_media(media_id=id)
redirect("/recent")

@route('/media_unlike/<id>')
def media_unlike(session,id):
access_token = session.get('access_token')
def media_unlike(id):
access_token = request.session['access_token']
api = client.InstagramAPI(access_token=access_token)
api.unlike_media(media_id=id)
redirect("/recent")

@route('/user_media_feed')
def on_user_media_feed(session):
access_token = session.get('access_token')
def on_user_media_feed():
access_token = request.session['access_token']
content = "<h2>User Media Feed</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -119,13 +127,13 @@ def on_user_media_feed(session):
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
counter += 1
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/location_recent_media')
def location_recent_media(session):
access_token = session.get('access_token')
def location_recent_media():
access_token = request.session['access_token']
content = "<h2>Location Recent Media</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -136,13 +144,13 @@ def location_recent_media(session):
for media in recent_media:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/media_search')
def media_search(session):
access_token = session.get('access_token')
def media_search():
access_token = request.session['access_token']
content = "<h2>Media Search</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -153,13 +161,13 @@ def media_search(session):
for media in media_search:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/media_popular')
def media_popular(session):
access_token = session.get('access_token')
def media_popular():
access_token = request.session['access_token']
content = "<h2>Popular Media</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -170,13 +178,13 @@ def media_popular(session):
for media in media_search:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/user_search')
def user_search(session):
access_token = session.get('access_token')
def user_search():
access_token = request.session['access_token']
content = "<h2>User Search</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -187,13 +195,13 @@ def user_search(session):
for user in user_search:
users.append('<li><img src="%s">%s</li>' % (user.profile_picture,user.username))
content += ''.join(users)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/user_follows')
def user_follows(session):
access_token = session.get('access_token')
def user_follows():
access_token = request.session['access_token']
content = "<h2>User Follows</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -209,13 +217,13 @@ def user_follows(session):
for user in user_follows:
users.append('<li><img src="%s">%s</li>' % (user.profile_picture,user.username))
content += ''.join(users)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/location_search')
def location_search(session):
access_token = session.get('access_token')
def location_search():
access_token = request.session['access_token']
content = "<h2>Location Search</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -226,13 +234,13 @@ def location_search(session):
for location in location_search:
locations.append('<li>%s <a href="https://www.google.com/maps/preview/@%s,%s,19z">Map</a> </li>' % (location.name,location.point.latitude,location.point.longitude))
content += ''.join(locations)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/tag_search')
def tag_search(session):
access_token = session.get('access_token')
def tag_search():
access_token = request.session['access_token']
content = "<h2>Tag Search</h2>"
if not access_token:
return 'Missing Access Token'
Expand All @@ -244,8 +252,8 @@ def tag_search(session):
for tag_media in tag_recent_media:
photos.append('<img src="%s"/>' % tag_media.get_standard_resolution_url())
content += ''.join(photos)
except Exception, e:
print e
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)

@route('/realtime_callback')
Expand All @@ -262,6 +270,6 @@ def on_realtime_callback():
try:
reactor.process(CONFIG['client_secret'], raw_response, x_hub_signature)
except subscriptions.SubscriptionVerifyError:
print "Signature mismatch"
print("Signature mismatch")

run(host='localhost', port=8515, reloader=True)
bottle.run(app=app, host='localhost', port=8515, reloader=True)

0 comments on commit 82e65c7

Please sign in to comment.