python-instagram是github上面的一个专门用来获取instagram的API的库。地址:https://github.com/Instagram/python-instagram
我们的示例将从SAE开始。框架为Flask。
1.首先获取应用的client_id和client_scret.
CONFIG = { "client_id": "9ef948a67d514ed0b6bb46166cf7400b", "client_secret": "d010d40a8a9247b9996bb55c2d831ce5", "redirect_uri": "http://1.lovey.sinaapp.com/instagramfetch" }
2. 取出python-instagram代码中的instagram文件夹,放到根目录下。
然后代码中进行订阅。
unauthenticated_api = client.InstagramAPI(**CONFIG) reactor = subscriptions.SubscriptionsReactor() reactor.register_callback(subscriptions.SubscriptionType.TAG, process_tag_update)
3. 在用户点击登录之后,重定向用户到instagram的授权页面。
如下通过code来获取access_token,并通过access_token来获取用户的媒体信息。
@app.route('/redirect_instagram') def redirect_instagram(): url = unauthenticated_api.get_authorize_url( scope = ["likes", "comments"]) return redirect( url )
4. 随后instagram会将用来获取access_token的code响应到你的回调地址。
@app.route('/instagramfetch') def on_callback(): code = request.args.get("code") if not code: return render_template('instagram_photos.html',content = "error") try: access_token = unauthenticated_api.exchange_code_for_access_token( code ) if not access_token: return render_template('instagram_photos.html',content = "error") api = client.InstagramAPI(access_token = access_token[0] ) content = api.user_recent_media() recent_media, next = api.user_recent_media() #return render_template( 'instagram_photos.html', content=content ) photos = [] for media in recent_media: photos.append('<img src="%s" />' %media.images['thumbnail'].url ) return ''.join(photos) except Exception, e: return render_template('instagram_photos.html', content = e )