Skip to content

Instantly share code, notes, and snippets.

@xen
Created April 12, 2013 05:44
Show Gist options
  • Select an option

  • Save xen/5369706 to your computer and use it in GitHub Desktop.

Select an option

Save xen/5369706 to your computer and use it in GitHub Desktop.
Flask Github methods calls
from flask import Flask, redirect, url_for, session, request
from flask_oauth import OAuth
SECRET_KEY = 'development key'
DEBUG = True
GITHUB_CLIENT_ID = '<Client-ID>'
GITHUB_CLIENT_SECRET = '<Client-Secret>'
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()
github = oauth.remote_app('github',
base_url='https://api.github.com/',
request_token_url=None,
access_token_url='https://github.com/login/oauth/access_token',
authorize_url='https://github.com/login/oauth/authorize',
consumer_key=GITHUB_CLIENT_ID,
consumer_secret=GITHUB_CLIENT_SECRET,
# add scope like this: {'scope': 'user:email'}
request_token_params=None
)
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
return github.authorize(callback=url_for('github_authorized',
next=request.args.get('next') or request.referrer or None,
_external=True))
@app.route('/login/authorized')
@github.authorized_handler
def github_authorized(resp):
if resp is None:
return 'Access denied: error=%s' % (request.args['error'])
session['oauth_token'] = (resp['access_token'], '')
user = github.get('/user')
return 'Logged in as id=%s login=%s redirect=%s' % \
(user.data['id'], user.data['login'], request.args.get('next'))
@app.route('/repos')
def repos():
# only logged in user should call it, but I skip it in this example
resp = github.get('/user/repos', data = {'type': 'public'})
print(resp.data) # should print to console
@app.route('/addhook/<path:full_name>')
def repos(full_name):
# only logged in user should call it, but I skip it in this example
HOOK_URL = 'http://example.com/hook'
resp = github.post('/repos/%(full_name)s/hooks' % {'full_name': full_name},
data = {
'name':'web',
'active': True,
'events': ['push'],
'config': {
'url': HOOK_URL,
'content_type': 'json'
}
},
format = 'json'
)
print(resp.status, resp.data)
@github.tokengetter
def get_github_oauth_token():
return session.get('oauth_token')
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment