Flaskのチュートリアルの認証をFlask-OAuthを使ったものに変えてみた。
loginのとこを変えるのと、新しくoauth-authorized,get_twitter_tokenというメソッドを追加してoauthの認証に対応させただけ。
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing
from flaskext.oauth import OAuth
DATABASE = '/Users/kzfm/flask/flaskr/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
app = Flask(__name__)
app.config.from_object(__name__)
oauth = OAuth()
twitter = oauth.remote_app('twitter',
base_url='http://api.twitter.com/1/',
request_token_url='http://api.twitter.com/oauth/request_token',
access_token_url='http://api.twitter.com/oauth/access_token',
authorize_url='http://api.twitter.com/oauth/authorize',
consumer_key='XXXXXXXXXXXXXXXXX',
consumer_secret='XXXXXXXXXXXXX'
)
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.after_request
def after_request(response):
g.db.close()
return response
@twitter.tokengetter
def get_twitter_token():
return session.get('twitter_token')
@app.route('/')
def show_entries():
cur = g.db.execute('select title, text from entries order by id desc')
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
return render_template('show_entries.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
g.db.commit()
return redirect(url_for('show_entries'))
@app.route('/login')
def login():
sys.stderr.write(url_for("oauth_authorized"))
return twitter.authorize(callback=url_for("oauth_authorized"))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
@app.route('/oauth-authorized')
@twitter.authorized_handler
def oauth_authorized(resp):
next_url = url_for('show_entries')
if resp is None:
flash(u'You denied the request to sign in.')
return redirect(next_url)
session['logged_in'] = True
session['username'] = resp['screen_name']
flash(resp['screen_name'] + ' were signed in')
return redirect(next_url)
if __name__ == '__main__':
app.run()
手元のmacbookで書いてたんだけど、localhostだとcallbackでエラー吐くので、sunshine.private.jpとか適当なホストネームを127.0.0.1にあてといた。