Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
7kai Tasks OAuth sample code for Python.
#!/usr/bin/env python
# encoding:utf-8
# easy_install Flask
# easy_install oauth2
from flask import Flask, session, redirect, url_for, escape, request, Response
import oauth2
import urlparse
import urllib
import json
API_URL = ''
consumer = oauth2.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
app = Flask(__name__)
def index():
request_token = getRequestToken(CALLBACK_URL)
session['request_token'] = request_token
return redirect('%s?oauth_token=%s' % (AUTHORIZE_URL, request_token.key))
def callback():
request_token = session['request_token']
access_token = getAccessToken(request_token);
session['access_token'] = access_token
return redirect('/me')
def me():
access_token = session['access_token']
account = getProtectedResource(access_token, API_URL, 'GET')
return Response(json.dumps(account, indent=4, ensure_ascii=False), mimetype='text/plain')
def getRequestToken(callback_url):
client = oauth2.Client(consumer)
body = urllib.urlencode({'oauth_callback': callback_url}) if callback_url else ''
resp, content = client.request(REQUEST_TOKEN_URL, 'POST', body=body)
return oauth2.Token.from_string(content)
def getAccessToken(request_token):
client = oauth2.Client(consumer, request_token)
resp, content = client.request(ACCESS_TOKEN_URL, 'POST')
return oauth2.Token.from_string(content)
def getProtectedResource(access_token, url, method, parameters=None):
client = oauth2.Client(consumer, access_token)
body = urllib.urlencode(parameters) if parameters else ''
resp, content = client.request(url, method, body=body)
return json.loads(content, 'utf-8')
app.debug = True
app.secret_key = ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.