Create a gist now

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
REQUEST_TOKEN_URL = 'https://tasks.7kai.org/oauth/request_token'
AUTHORIZE_URL = 'https://tasks.7kai.org/oauth/authorize'
ACCESS_TOKEN_URL = 'https://tasks.7kai.org/oauth/access_token'
API_URL = 'https://tasks.7kai.org/api/1/account/me'
CALLBACK_URL = 'http://127.0.0.1:5000/callback'
CONSUMER_KEY = 'YOUR_APP_CONSUMER_KEY'
CONSUMER_SECRET = 'YOUR_APP_CONSUMER_SECRET'
consumer = oauth2.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
app = Flask(__name__)
@app.route("/")
def index():
request_token = getRequestToken(CALLBACK_URL)
session['request_token'] = request_token
return redirect('%s?oauth_token=%s' % (AUTHORIZE_URL, request_token.key))
@app.route('/callback')
def callback():
request_token = session['request_token']
request_token.set_verifier(request.args.get('oauth_verifier'))
access_token = getAccessToken(request_token);
session['access_token'] = access_token
return redirect('/me')
@app.route('/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 = '7ka-tasks-oauth-python.py'
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment