如何通过Flask应用程序为谷歌应用程序脚本API(或谷歌云平台)获取新的token.json



我有一个flask应用程序,我想验证它以使用google应用程序脚本API。如果我用这个快速启动链接创建了一个token.json文件,它会把我带到身份验证页面,然后为我创建一个token.json文件——即使我已经删除了它或它过期了。这就是我想在我的flask应用程序中做的(因为代币过期了,所以我希望能够刷新它们(。我使用的代码是

# Setup the Apps Script API scopes
SCOPES = ['https://www.googleapis.com/auth/script.projects',
'https://www.googleapis.com/auth/script.external_request',
'https://www.googleapis.com/auth/spreadsheets']
def getCredentialsAppScript():
store = oauth_file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
return creds

然后在getListItems(代码片段(中

@app.route("/getListItems", methods=["POST", "GET"])
def getListItems():

"""Runs the sample.
"""
SCRIPT_ID = 'xxxxxxxxxxxxxx'
creds = getCredentialsAppScript()
service = build('script', 'v1', credentials=creds)
# Create an execution request object.
request = {"function": "getTokensForUser"}

错误只是说UserWarning: Cannot access token.json: No such file or directory我不明白的是为什么我不能通过flask应用程序中的代码块获得新的token.json,但是当运行quickstart.py时,如果我没有token.json.,它会把我带到谷歌登录页面

if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)

我认为您可能缺少关于OAuth2及其在Google API中的实现的一些信息。

我强烈建议您阅读服务器端OAuth的文档,甚至在flank中有授权、令牌撤销和API测试调用的完整示例。


具体来说,代码的问题是将结构复制为python快速启动,但您必须记住,快速启动是作为命令行程序执行的,而不是像Flask那样作为服务器端执行。

因此,因为您现在处于服务器环境中,您首先需要将用户重定向到谷歌授权页面:

# Copied from https://developers.google.com/identity/protocols/oauth2/web-server#python_5
@app.route('/authorize')
def authorize():
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
# The URI created here must exactly match one of the authorized redirect URIs
# for the OAuth 2.0 client, which you configured in the API Console. If this
# value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
# error.
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')
# Store the state so the callback can verify the auth server response.
flask.session['state'] = state
return flask.redirect(authorization_url)

然后在oauth2callback函数中接收授权对象:

# Copied from https://developers.google.com/identity/protocols/oauth2/web-server#python_5
@app.route('/oauth2callback')
def oauth2callback():
# Specify the state when creating the flow in the callback so that it can
# verified in the authorization server response.
state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
# Use the authorization server's response to fetch the OAuth 2.0 tokens.
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
# Store credentials in the session.
# ACTION ITEM: In a production app, you likely want to save these
#              credentials in a persistent database instead.
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials)
return flask.redirect(flask.url_for('<Your function calling the API>'))

最新更新