{% raw %}

使用 Twitter 登录 Flask 应用

原文: https://pythonspot.com/login-to-flask-app-with-twitter/

在本教程中,您将学习如何在 Flask 应用程序中使用 Twitter 进行登录身份验证。 您可以使用 Twitter 对网站进行身份验证,而不是使用自定义用户登录系统。 您的访客可能已经在 Twitter 上拥有一个帐户,那么为什么不使用它登录呢?

为此,我们使用称为 OAuth 的协议。 从维基百科:

OAuth 是一种使用令牌来代表资源所有者访问资源的协议。 考虑使用户能够对网站的某些部分发出代客密钥。 许多网站,例如 Google,Facebook 和 Twitter,都使用 OAuth 来认证第三方客户端,以便访问某些用户资源。

如果听起来含糊,请放心,我们将逐步指导您。

代码

创建文件app.py,并设置您从 Twitter 获得的consumer_keyconsumer_secret

  1. from flask import Flask, request, redirect, url_for, session, g, flash, \
  2. render_template
  3. from flask_oauth import OAuth
  4. from sqlalchemy import create_engine, Column, Integer, String
  5. from sqlalchemy.orm import scoped_session, sessionmaker
  6. from sqlalchemy.ext.declarative import declarative_base
  7. # configuration
  8. SECRET_KEY = 'development key'
  9. DEBUG = True
  10. # setup flask
  11. app = Flask(__name__)
  12. app.debug = DEBUG
  13. app.secret_key = SECRET_KEY
  14. oauth = OAuth()
  15. # Use Twitter as example remote application
  16. twitter = oauth.remote_app('twitter',
  17. # unless absolute urls are used to make requests, this will be added
  18. # before all URLs. This is also true for request_token_url and others.
  19. base_url='https://api.twitter.com/1/',
  20. # where flask should look for new request tokens
  21. request_token_url='https://api.twitter.com/oauth/request_token',
  22. # where flask should exchange the token with the remote application
  23. access_token_url='https://api.twitter.com/oauth/access_token',
  24. # twitter knows two authorizatiom URLs. /authorize and /authenticate.
  25. # they mostly work the same, but for sign on /authenticate is
  26. # expected because this will give the user a slightly different
  27. # user interface on the twitter side.
  28. authorize_url='https://api.twitter.com/oauth/authenticate',
  29. # the consumer keys from the twitter application registry.
  30. consumer_key='ADD TWITTER CONSUMER KEY',
  31. consumer_secret='ADD TWITTER CONSUMER SECRET'
  32. )
  33. @twitter.tokengetter
  34. def get_twitter_token(token=None):
  35. return session.get('twitter_token')
  36. @app.route('/')
  37. def index():
  38. access_token = session.get('access_token')
  39. if access_token is None:
  40. return redirect(url_for('login'))
  41. access_token = access_token[0]
  42. return render_template('index.html')
  43. @app.route('/login')
  44. def login():
  45. return twitter.authorize(callback=url_for('oauth_authorized',
  46. next=request.args.get('next') or request.referrer or None))
  47. @app.route('/logout')
  48. def logout():
  49. session.pop('screen_name', None)
  50. flash('You were signed out')
  51. return redirect(request.referrer or url_for('index'))
  52. @app.route('/oauth-authorized')
  53. @twitter.authorized_handler
  54. def oauth_authorized(resp):
  55. next_url = request.args.get('next') or url_for('index')
  56. if resp is None:
  57. flash(u'You denied the request to sign in.')
  58. return redirect(next_url)
  59. access_token = resp['oauth_token']
  60. session['access_token'] = access_token
  61. session['screen_name'] = resp['screen_name']
  62. session['twitter_token'] = (
  63. resp['oauth_token'],
  64. resp['oauth_token_secret']
  65. )
  66. return redirect(url_for('index'))
  67. if __name__ == '__main__':
  68. app.run()

使用文件index.html创建目录/templates/

  1. {% block body %};
  2. <h2>Flask Login App</h2>
  3. {% if session['screen_name'] %};
  4. Hello {{ session['screen_name'] };};!
  5. {% else %};
  6. Sign in with twitter.
  7. <a href="{{ url_for('login') };};"><img src="{{
  8. url_for('static', filename='sign-in.png') };}; alt="sign in"></a>
  9. {% endif %};
  10. {% endblock %};

最后,使用图像sign-in.png创建目录/static/

54.md - 图1

通过以下方式启动您的应用:

  1. python app.py

在您的网络浏览器中打开该应用程序。 然后,您的用户只需按照以下步骤登录:

54.md - 图2

Flask Twitter 登录界面

54.md - 图3

Flask OAuth Twitter

54.md - 图4

Twitter OAuth

下载 Flask 示例

{% endraw %}