gpt4 book ai didi

python - Google Sheets API json 文件 - CLIENT_SECRET 和 oauth2client 凭据之间有什么区别?

转载 作者:行者123 更新时间:2023-12-01 22:08:37 24 4
gpt4 key购买 nike

我遵循了 Google Sheet Python API 快速入门指南 ( https://developers.google.com/sheets/api/quickstart/python ),并能够使用他们提供的代码使其正常工作:

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'my/path/client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

credential_path = 'my/path/sheets.googleapis.com-python-quickstart.json'

store = Storage(credential_path)
credentials = store.get()

## !!!!! Is this needed?
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)

return credentials

在默认设置中,我下载了两个 JSON 文件:

  • client_secret.JSON
    • 已下载到项目目录。
  • sheets.googleapis.com-python-quickstart.JSON
    • 下载到~/.credentials目录

sheets.googleapis.com JSON 文件开头为:

"_module": "oauth2client.client".

问题 1:每个 JSON 文件的用途是什么?

问题 2:成功使用 Google Sheets API 是否需要这两个 JSON 文件?

  • 我认为不会,因为我无需 client_secret.JSON 文件即可使 API 正常工作。

最佳答案

这个答案怎么样?我认为当您了解 OAuth2 检索访问 token 和刷新 token 的过程时,您就可以理解这两个文件的含义。使用OAuth2检索访问 token 和刷新 token 的流程如下。

流程:

  1. 从 API 控制台下载 client_secret.JSON
    • client_secret.JSON 包括 client_idclient_secretredirect_uris
  2. 使用范围和 client_idclient_secret.JSON 检索授权代码。
  3. 使用授权代码、client_idclient_secretredirect_uris 检索访问 token 和刷新 token 。
    • 检索到的访问 token 、刷新 token 和其他参数将保存到 sheets.googleapis.com-python-quickstart.JSON 文件中。

注意:

  • 当您第一次运行快速入门时,将启动使用浏览器的授权流程。此时,Quickstart 的脚本使用 client_id 和范围检索授权码,然后使用授权码、client_id 检索访问 token 和刷新 token >client_secretredirect_uris
  • 首次运行快速入门后,将通过刷新 token 从 sheets.googleapis.com-python-quickstart.JSON 检索访问 token 。这样,就不需要使用浏览器检索授权码了。因此,当存在 sheets.googleapis.com-python-quickstart.JSON 时,则不需要 client_secret.JSON
    • 我认为这可以解答您的问题 2。
  • 但是,如果您想要更改 client_secret.JSON 的范围和/或凭据,则需要使用浏览器进行授权过程并检索授权代码。为此,您必须删除 sheets.googleapis.com-python-quickstart.JSON 并再次授权。当时,在快速入门中,再次使用 client_secret.JSON

引用文献:

如果这对您没有用,我很抱歉。

关于python - Google Sheets API json 文件 - CLIENT_SECRET 和 oauth2client 凭据之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com