获得Instagram访问令牌

时间:2014-10-07 17:46:18

标签: python instagram python-requests

嗨,你们有关于如何从python获取访问令牌的想法吗?

我的代码是这样的:

import bottle_session
import bottle
import cgi,os
from bottle import route, redirect, post, run, request
from instagram import client, subscriptions
import urllib
from pygeocoder import Geocoder

results = Geocoder.geocode("University of Santo Tomas,Manila,Philippines")
print(results[0].coordinates)

latitude=results[0].latitude
longitude=results[0].longitude 

CONFIG = {
    'client_id': '',
    'client_secret': '',
    'redirect_uri': 'localhost:8515/oauth_callback'
}

unauthenticated_api = client.InstagramAPI(**CONFIG)

url = unauthenticated_api.get_authorize_url(scope=["likes","comments"])

code = request.GET.get("code")
print "CODE:" + str(code)

access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
print "access token= " + access_token
print access_token

api = client.InstagramAPI(access_token=access_token)
session['access_token']=access_token

1 个答案:

答案 0 :(得分:1)

这就是我在Django中做同样的事情:

SCOPE = ('basic', 'comments', 'relationships', 'likes')


def get_api(access_token=None):
    if access_token is not None:
        # authenticated api
        return InstagramAPI(access_token=access_token)
    else:
        # unauthenticated api
        return InstagramAPI(client_id=CLIENT_ID,
                            client_secret=CLIENT_SECRET,
                            redirect_uri=REDIRECT_URL)


def logout(request):
    try:
        del request.session['token']
        del request.session['instagram_user']
    except KeyError:
        pass
    return redirect(REDIRECT_URL)


def signin(request):
    api = get_api()
    redirect_uri = api.get_authorize_login_url(scope=SCOPE)
    return HttpResponseRedirect(redirect_uri)

# Redirect url goes here
def instagram(request):
    template = 'account/instagram.html'
    access_token = request.session.get('token')
    instagram_user = request.session.get('instagram_user')

    if not access_token:
        code = request.GET.get("code")

        if not code:
            t = loader.get_template(template)
            c = RequestContext(request, {})
            return HttpResponse(t.render(c))

        unauthenticated_api = get_api()
        access_token, instagram_user = (
            unauthenticated_api.exchange_code_for_access_token(code))
        request.session['token'] = access_token
        request.session['instagram_user'] = instagram_user
        if not access_token:
            return HttpResponse('Could not get access token')

    api = get_api(access_token)
    instagram_user = api.user(instagram_user['id'])

    t = loader.get_template(template)
    c = RequestContext(request, {'insta_user': instagram_user})
    return HttpResponse(t.render(c))

希望这有帮助