【发布时间】:2013-12-17 14:25:49
【问题描述】:
我正在使用 Flask-oauthlib 连接到多个 API(例如 Twitter、GitHub 等)。目前,我将这些服务中的每一项都作为单独的蓝图。在每个服务的视图文件中,都有相同的三个视图:login、authorized 和 get_token。现在的代码不是很干,但我很难理解如何集中这些视图(从概念上讲)。
我怎样才能让这个更干燥?我想从概念上理解,而不是有人真正为我编写代码。
以下是一些可能会有所帮助的项目。这是应用程序结构:
- App
- Services
- FourSquare BP
- GitHub BP
- Twitter BP
- ...
- Other BPs
通用 API 视图可能会归入Services/api_views.py
这是一个 API 蓝图视图文件 (Twitter) 的示例。
twitter = Blueprint('twitter', __name__, url_prefix='/twitter')
bp = twitter
bp.api = TwitterAPI()
bp.oauth = bp.api.oauth_app
# Below here is the exact same for each file.
@bp.route('/')
@login_required
def login():
if current_user.get(bp.name, None):
return redirect(url_for('frontend.index'))
return bp.oauth.authorize(callback=url_for('.authorized', _external=True))
@bp.route('/authorized')
@bp.oauth.authorized_handler
def authorized(resp):
if resp is None:
flash(u'You denied the request to sign in.')
return redirect(url_for('frontend.index'))
if bp.oauth_type == 'oauth2':
resp['access_token'] = (resp['access_token'], '')
current_user[bp.name] = resp
current_user.save()
flash('You were signed in to %s' % bp.name.capitalize())
return redirect(url_for('frontend.index'))
@bp.oauth.tokengetter
def get_token(token=None):
if bp.oauth_type == 'oauth2':
return current_user.get(bp.name, None)['access_token']
return current_user.get(bp.name, None)['oauth_token']
我尝试将视图放在一个类中然后导入它们,但是在使用各种装饰器时遇到了问题(oauth 装饰器最麻烦)。
【问题讨论】: