使用flask、requests和oauthlib进行有风格的oauth舞蹈
Flask-Dance的Python项目详细描述
烧瓶舞
使用flask、requests和oauthlib进行oauth舞蹈。目前, 只支持OAuth使用者,但是这个项目可以很容易地支持 oauth的提供者在未来也一样。在full documentation for this project is hosted on ReadTheDocs, 包括supported OAuth providers的完整列表, 但是这个自述文件会让你体验一下这些功能。
快速启动
如果您希望您的用户能够从 supported OAuth providers你很容易做到下面是一个使用github的示例:
fromflaskimportFlask,redirect,url_forfromflask_dance.contrib.githubimportmake_github_blueprint,githubapp=Flask(__name__)app.secret_key="supersekrit"blueprint=make_github_blueprint(client_id="my-key-here",client_secret="my-secret-here",)app.register_blueprint(blueprint,url_prefix="/login")@app.route("/")defindex():ifnotgithub.authorized:returnredirect(url_for("github.login"))resp=github.get("/user")assertresp.okreturn"You are @{login} on GitHub".format(login=resp.json()["login"])
如果你很想尝试一下,请查看flask-dance-github示例 存储库,以及如何运行此代码的详细说明
github对象是一个context local,就像flask.request。那意味着 您可以将它导入到任何想要的python文件中,并在上下文中使用它 传入的HTTP请求的如果你把你的烧瓶应用程序分成多个 不同的文件,可以随意将此对象导入到任何文件中,并使用 就像使用requests模块一样。
你也可以和任何你喜欢的OAuth提供者一起使用Flask Dance,而不仅仅是 预设配置。See the documentation for how to use other OAuth providers.
仓库
默认情况下,OAuth访问令牌存储在Flask的会话对象中。 这意味着如果用户清除了浏览器cookie,他们将 必须再跳一遍非统组织舞,这不好。 最好存储访问令牌 在数据库或其他持久性存储中,flask dance支持 交换令牌存储。例如,如果您使用SQLAlchemy, 设置如下:
fromflask_sqlalchemyimportSQLAlchemyfromflask_dance.consumer.storage.sqlaimportOAuthConsumerMixin,SQLAlchemyStoragedb=SQLAlchemy()classUser(db.Model):id=db.Column(db.Integer,primary_key=True)# ... other columns as neededclassOAuth(OAuthConsumerMixin,db.Model):user_id=db.Column(db.Integer,db.ForeignKey(User.id))user=db.relationship(User)# get_current_user() is a function that returns the current logged in userblueprint.storage=SQLAlchemyStorage(OAuth,db.session,user=get_current_user)
SQLAlchemy存储与Flask-SQLAlchemy无缝集成, 以及用于用户管理的Flask-Login,以及用于缓存的Flask-Caching
完整文档
这个自述文件提供了一个什么样的烧瓶舞的能力为了看到更多, read the documentation on ReadTheDocs。