首页 > 解决方案 > 使用 Flask-Dance-SQLA 完成 OAuth 舞蹈后,使用实际 API 的最佳方法是什么?

问题描述

我正在工作:https ://github.com/singingwolfboy/flask-dance-google-sqla并让 OAuth 模板开始工作。

我一直在尝试获取一些代码来使用 Google Calendar API,使用模板设置方式来做到这一点的最佳方法是什么?

这是定向的正确方法吗?或者是否有一个带有附加标头的会话对象可以直接使用?

我一直在尝试获取令牌(来自 SQLAlchemy 数据库)并执行 requests.post 之类的操作,但返回 Not Found。

def get_token():
    return OAuth.query.filter_by(user_id=current_user.id).first().token

@app.route("/get_events")
def get_events():
    token = str(get_token())
    req = requests.post('https://www.googleapis.com/calendar/v3', headers={'Authorization': token})

标签: pythonflaskflask-dance

解决方案


google使用Flask-Dance 提供的会话对象要容易得多,如下所示:

from flask_dance.contrib.google import google

@app.route("/get_events")
def get_events():
    if not google.authorized:
        return redirect(url_for("google.login"))
    req = google.post("/calendar/v3")
    # ... do whatever you want with this data

会话对象将google自动从存储中加载 OAuth 令牌——在你的例子中是 SQLAlchemy。但是,它只能在令牌在过去某个时间点存储的情况下加载它,这就是为什么检查是个好主意google.authorized——如果它是假的,那么就没有令牌。

那有意义吗?


推荐阅读