Skip to content
This repository was archived by the owner on Jan 13, 2022. It is now read-only.

Commit 82e65c7

Browse files
author
Jon Heaton
committed
python3 compat changes
1 parent dee95d8 commit 82e65c7

5 files changed

Lines changed: 82 additions & 70 deletions

File tree

get_access_token.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,17 @@
1414
except Exception:
1515
pass
1616

17-
client_id = raw_input("Client ID: ").strip()
18-
client_secret = raw_input("Client Secret: ").strip()
19-
redirect_uri = raw_input("Redirect URI: ").strip()
20-
raw_scope = raw_input("Requested scope (separated by spaces, blank for just basic read): ").strip()
17+
# Fix Python 2.x.
18+
try:
19+
import __builtin__
20+
input = getattr(__builtin__, 'raw_input')
21+
except (ImportError, AttributeError):
22+
pass
23+
24+
client_id = input("Client ID: ").strip()
25+
client_secret = input("Client Secret: ").strip()
26+
redirect_uri = input("Redirect URI: ").strip()
27+
raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip()
2128
scope = raw_scope.split(' ')
2229
# For basic, API seems to need to be set explicitly
2330
if not scope or scope == [""]:
@@ -26,10 +33,11 @@
2633
api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
2734
redirect_uri = api.get_authorize_login_url(scope = scope)
2835

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

31-
code = raw_input("Paste in code in query string after redirect: ").strip()
38+
code = (str(input("Paste in code in query string after redirect: ").strip()))
3239

3340
access_token = api.exchange_code_for_access_token(code)
34-
print "access token:\n", access_token
41+
print ("access token: " )
42+
print (access_token)
3543

instagram/bind.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,23 +122,19 @@ def _do_api_request(self, url, method="GET", body=None, headers=None):
122122
ips = self.api.client_ips
123123
signature = hmac.new(secret, ips, sha256).hexdigest()
124124
headers['X-Insta-Forwarded-For'] = '|'.join([ips, signature])
125-
126125
response, content = OAuth2Request(self.api).make_request(url, method=method, body=body, headers=headers)
127126
if response['status'] == '503' or response['status'] == '429':
128127
raise InstagramAPIError(response['status'], "Rate limited", "Your client is making too many request per second")
129-
130128
try:
131-
content_obj = simplejson.loads(content)
129+
content_obj = simplejson.loads(content.decode())
132130
except ValueError:
133131
raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status'])
134-
135132
# Handle OAuthRateLimitExceeded from Instagram's Nginx which uses different format to documented api responses
136133
if 'meta' not in content_obj:
137134
if content_obj.get('code') == 420 or content_obj.get('code') == 429:
138135
error_message = content_obj.get('error_message') or "Your client is making too many request per second"
139136
raise InstagramAPIError(content_obj.get('code'), "Rate limited", error_message)
140137
raise InstagramAPIError(content_obj.get('code'), content_obj.get('error_type'), content_obj.get('error_message'))
141-
142138
api_responses = []
143139
status_code = content_obj['meta']['code']
144140
self.api.x_ratelimit_remaining = response.get("x-ratelimit-remaining",None)

instagram/oauth2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def exchange_for_access_token(self, code=None, username=None, password=None, sco
108108
http_object = Http(disable_ssl_certificate_validation=True)
109109
url = self.api.access_token_url
110110
response, content = http_object.request(url, method="POST", body=data)
111-
parsed_content = simplejson.loads(content)
111+
parsed_content = simplejson.loads(content.decode())
112112
if int(response['status']) != 200:
113113
raise OAuth2AuthExchangeError(parsed_content.get("error_message", ""))
114114
return parsed_content['access_token'], parsed_content['user']

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
bottle==0.12.7
2-
bottle-session==0.3
32
httplib2==0.9
43
python-instagram==1.1.3
54
redis==2.10.3
65
simplejson==3.6.3
76
wsgiref==0.1.2
7+
beaker==1.6.4

sample_app.py

Lines changed: 64 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
1-
import bottle_session
21
import bottle
3-
from bottle import route, redirect, post, run, request
2+
import beaker.middleware
3+
from bottle import route, redirect, post, run, request, hook
44
from instagram import client, subscriptions
55

66
bottle.debug(True)
77

8-
app = bottle.app()
9-
plugin = bottle_session.SessionPlugin(cookie_lifetime=600)
10-
app.install(plugin)
8+
session_opts = {
9+
'session.type': 'file',
10+
'session.data_dir': './session/',
11+
'session.auto': True,
12+
}
13+
14+
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
1115

1216
CONFIG = {
1317
'client_id': '<client_id>',
@@ -17,8 +21,12 @@
1721

1822
unauthenticated_api = client.InstagramAPI(**CONFIG)
1923

24+
@hook('before_request')
25+
def setup_request():
26+
request.session = request.environ['beaker.session']
27+
2028
def process_tag_update(update):
21-
print update
29+
print(update)
2230

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

3442
def get_nav():
3543
nav_menu = ("<h1>Python Instagram</h1>"
@@ -48,25 +56,25 @@ def get_nav():
4856
return nav_menu
4957

5058
@route('/oauth_callback')
51-
def on_callback(session):
59+
def on_callback():
5260
code = request.GET.get("code")
5361
if not code:
5462
return 'Missing code'
5563
try:
5664
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
57-
print "access token= " + access_token
5865
if not access_token:
5966
return 'Could not get access token'
6067
api = client.InstagramAPI(access_token=access_token)
61-
session['access_token']=access_token
62-
except Exception, e:
63-
print e
68+
request.session['access_token'] = access_token
69+
print ("access token="+access_token)
70+
except Exception as e:
71+
print(e)
6472
return get_nav()
6573

6674
@route('/recent')
67-
def on_recent(session):
68-
access_token = session.get('access_token')
75+
def on_recent():
6976
content = "<h2>User Recent Media</h2>"
77+
access_token = request.session['access_token']
7078
if not access_token:
7179
return 'Missing Access Token'
7280
try:
@@ -79,30 +87,30 @@ def on_recent(session):
7987
photos.append('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url()))
8088
else:
8189
photos.append('<img src="%s"/>' % (media.get_low_resolution_url()))
82-
print media
90+
print(media)
8391
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))
8492
content += ''.join(photos)
85-
except Exception, e:
86-
print e
93+
except Exception as e:
94+
print(e)
8795
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
8896

8997
@route('/media_like/<id>')
90-
def media_like(session,id):
91-
access_token = session.get('access_token')
98+
def media_like(id):
99+
access_token = request.session['access_token']
92100
api = client.InstagramAPI(access_token=access_token)
93101
api.like_media(media_id=id)
94102
redirect("/recent")
95103

96104
@route('/media_unlike/<id>')
97-
def media_unlike(session,id):
98-
access_token = session.get('access_token')
105+
def media_unlike(id):
106+
access_token = request.session['access_token']
99107
api = client.InstagramAPI(access_token=access_token)
100108
api.unlike_media(media_id=id)
101109
redirect("/recent")
102110

103111
@route('/user_media_feed')
104-
def on_user_media_feed(session):
105-
access_token = session.get('access_token')
112+
def on_user_media_feed():
113+
access_token = request.session['access_token']
106114
content = "<h2>User Media Feed</h2>"
107115
if not access_token:
108116
return 'Missing Access Token'
@@ -119,13 +127,13 @@ def on_user_media_feed(session):
119127
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
120128
counter += 1
121129
content += ''.join(photos)
122-
except Exception, e:
123-
print e
130+
except Exception as e:
131+
print(e)
124132
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
125133

126134
@route('/location_recent_media')
127-
def location_recent_media(session):
128-
access_token = session.get('access_token')
135+
def location_recent_media():
136+
access_token = request.session['access_token']
129137
content = "<h2>Location Recent Media</h2>"
130138
if not access_token:
131139
return 'Missing Access Token'
@@ -136,13 +144,13 @@ def location_recent_media(session):
136144
for media in recent_media:
137145
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
138146
content += ''.join(photos)
139-
except Exception, e:
140-
print e
147+
except Exception as e:
148+
print(e)
141149
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
142150

143151
@route('/media_search')
144-
def media_search(session):
145-
access_token = session.get('access_token')
152+
def media_search():
153+
access_token = request.session['access_token']
146154
content = "<h2>Media Search</h2>"
147155
if not access_token:
148156
return 'Missing Access Token'
@@ -153,13 +161,13 @@ def media_search(session):
153161
for media in media_search:
154162
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
155163
content += ''.join(photos)
156-
except Exception, e:
157-
print e
164+
except Exception as e:
165+
print(e)
158166
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
159167

160168
@route('/media_popular')
161-
def media_popular(session):
162-
access_token = session.get('access_token')
169+
def media_popular():
170+
access_token = request.session['access_token']
163171
content = "<h2>Popular Media</h2>"
164172
if not access_token:
165173
return 'Missing Access Token'
@@ -170,13 +178,13 @@ def media_popular(session):
170178
for media in media_search:
171179
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
172180
content += ''.join(photos)
173-
except Exception, e:
174-
print e
181+
except Exception as e:
182+
print(e)
175183
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
176184

177185
@route('/user_search')
178-
def user_search(session):
179-
access_token = session.get('access_token')
186+
def user_search():
187+
access_token = request.session['access_token']
180188
content = "<h2>User Search</h2>"
181189
if not access_token:
182190
return 'Missing Access Token'
@@ -187,13 +195,13 @@ def user_search(session):
187195
for user in user_search:
188196
users.append('<li><img src="%s">%s</li>' % (user.profile_picture,user.username))
189197
content += ''.join(users)
190-
except Exception, e:
191-
print e
198+
except Exception as e:
199+
print(e)
192200
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
193201

194202
@route('/user_follows')
195-
def user_follows(session):
196-
access_token = session.get('access_token')
203+
def user_follows():
204+
access_token = request.session['access_token']
197205
content = "<h2>User Follows</h2>"
198206
if not access_token:
199207
return 'Missing Access Token'
@@ -209,13 +217,13 @@ def user_follows(session):
209217
for user in user_follows:
210218
users.append('<li><img src="%s">%s</li>' % (user.profile_picture,user.username))
211219
content += ''.join(users)
212-
except Exception, e:
213-
print e
220+
except Exception as e:
221+
print(e)
214222
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
215223

216224
@route('/location_search')
217-
def location_search(session):
218-
access_token = session.get('access_token')
225+
def location_search():
226+
access_token = request.session['access_token']
219227
content = "<h2>Location Search</h2>"
220228
if not access_token:
221229
return 'Missing Access Token'
@@ -226,13 +234,13 @@ def location_search(session):
226234
for location in location_search:
227235
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))
228236
content += ''.join(locations)
229-
except Exception, e:
230-
print e
237+
except Exception as e:
238+
print(e)
231239
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
232240

233241
@route('/tag_search')
234-
def tag_search(session):
235-
access_token = session.get('access_token')
242+
def tag_search():
243+
access_token = request.session['access_token']
236244
content = "<h2>Tag Search</h2>"
237245
if not access_token:
238246
return 'Missing Access Token'
@@ -244,8 +252,8 @@ def tag_search(session):
244252
for tag_media in tag_recent_media:
245253
photos.append('<img src="%s"/>' % tag_media.get_standard_resolution_url())
246254
content += ''.join(photos)
247-
except Exception, e:
248-
print e
255+
except Exception as e:
256+
print(e)
249257
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
250258

251259
@route('/realtime_callback')
@@ -262,6 +270,6 @@ def on_realtime_callback():
262270
try:
263271
reactor.process(CONFIG['client_secret'], raw_response, x_hub_signature)
264272
except subscriptions.SubscriptionVerifyError:
265-
print "Signature mismatch"
273+
print("Signature mismatch")
266274

267-
run(host='localhost', port=8515, reloader=True)
275+
bottle.run(app=app, host='localhost', port=8515, reloader=True)

0 commit comments

Comments
 (0)