Skip to content

Instantly share code, notes, and snippets.

@markpasc
Forked from lrvick/github_flask.py
Last active December 14, 2015 00:29
Show Gist options
  • Save markpasc/4999079 to your computer and use it in GitHub Desktop.
Save markpasc/4999079 to your computer and use it in GitHub Desktop.
Flask app using GitHub API (without rauth, just requests)
from urllib import urlencode
from urlparse import parse_qsl
from flask import Flask, request, redirect, url_for
import requests
GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'
GITHUB_ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token'
app = Flask(__name__)
app.debug = True
app.config.update(
GITHUB_CLIENT_ID='<your client id>',
GITHUB_CLIENT_SECRET='<your client secret>',
)
@app.route('/')
def index():
code = request.args.get('code',None)
if not code:
return redirect(url_for('login'))
print 'CODE: ',code
resp = requests.post(GITHUB_ACCESS_TOKEN_URL, params={
'client_id': app.config['GITHUB_CLIENT_ID'],
'client_secret': app.config['GITHUB_CLIENT_SECRET'],
'code': code,
})
access_token = dict(parse_qsl(resp.text))['access_token'] # KeyError if fails
print 'ACCESS_TOKEN: ',access_token
s = requests.Session()
s.headers['Authorization'] = 'token {}'.format(access_token)
resp = s.get('https://api.github.com/user')
print 'User: ', resp.json()
return "OK"
@app.route('/login')
def login():
query = urlencode({
'client_id': app.config['GITHUB_CLIENT_ID'],
'scope': 'repo', # or what have you
})
authorize_url = '?'.join((GITHUB_AUTHORIZE_URL, query))
print authorize_url
return redirect(authorize_url)
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment