Skip to content

Instantly share code, notes, and snippets.

@jasonlvhit
Last active August 29, 2015 13:56
Show Gist options
  • Save jasonlvhit/9290532 to your computer and use it in GitHub Desktop.
Save jasonlvhit/9290532 to your computer and use it in GitHub Desktop.
豆瓣OAuth2用户认证登录, Flask应用。
from sqlalchemy.exc import IntegrityError
from flask import g, request, session, redirect, flash
import urllib
import urllib2
from app import models
@app.route('/douban/login')
def get_auth_code():
return redirect("https://www.douban.com/service/auth2/auth?client_id=0fb837361a070e2d2f28a5a24e152a87&redirect_uri=https://douping.sinaapp.com/auth&response_type=code")
@app.route('/auth')
def auth():
"""
Douban OAuth2 authorization
Get the auth code and retrive the user info
"""
if request.args.has_key('error'):
return redirect("http://douping.sinaapp.com")
auth_code = request.args['code']
params = urllib.urlencode({'client_id': '0fb837361a070e2d2f28a5a24e152a87',
'code':auth_code,
'client_secret':'########',
'redirect_uri':'http://douping.sinaapp.com',
'grant_type': 'authorization_code'
})
try:
f = urllib.urlopen("https://www.douban.com/service/auth2/token", params)
except urllib2.URLError as e:
flash(e.reason)
return redirect("http://douping.sinaapp.com")
content = json.loads(f.read())
#POST
header = {"Authorization": "Bearer " + content["access_token"]}
req = urllib2.Request(url = "https://api.douban.com/v2/user/~me", headers = header)
try:
result = json.loads(urllib2.urlopen(req).read())
except urllib.URLError as e:
return redirect("http://douping.sinaapp.com")
user = models.User.query.filter_by(douban_id = result['id']).first()
if not user:
if result['avatar'].split('/')[-1] != 'user_normal.jpg':
avatar = "http://img3.douban.com/icon/ul" + result['avatar'].split('/')[-1].split('u')[-1]
else:
avatar = result['avatar']
try:
user = models.User(result['id'], result['name'], avatar, result['alt'])
db.session.add(user)
db.session.commit()
except IntegrityError:
db.session.rollback()
flash('Database error.')
return redirect("http://douping.sinaapp.com")
session['user_id'] = user.id
return redirect("http://douping.sinaapp.com")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment