Google表格API json文件 - CLIENT_SECRET和oauth2client凭据有什么区别?

问题描述 投票:1回答:1

我按照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 下载到project目录。
  • sheets.googleapis.com-python-quickstart.JSON 下载到~/.credentials目录

sheets.googleapis.com JSON文件以:

"_module": "oauth2client.client".

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

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

  • 我在想不,因为我能够在没有client_secret.JSON文件的情况下使用API​​。
python json api credentials google-sheets-api
1个回答
1
投票

这个答案怎么样?我想当您知道用于检索访问令牌和刷新令牌的OAuth2流程时,您可以理解这两个文件的含义。使用OAuth2检索访问令牌和刷新令牌的流程如下。

流 :

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

注意 :

  • 首次运行快速入门时,将启动使用浏览器的授权过程。那时,Quickstart的脚本使用client_id和scopes检索授权代码,然后使用授权代码client_idclient_secretredirect_uris检索访问令牌和刷新令牌。
  • 第一次运行Quickstart后,访问令牌由sheets.googleapis.com-python-quickstart.JSON的刷新令牌检索。这样,不需要使用浏览器检索授权代码。所以当有sheets.googleapis.com-python-quickstart.JSON时,不需要client_secret.JSON。 我认为这可以为您的问题2提供答案。
  • 但是,如果要更改client_secret.JSON的范围和/或凭据,则需要使用浏览器和检索授权代码的授权过程。为此,您必须删除sheets.googleapis.com-python-quickstart.JSON并再次授权。那时,在Quickstart,再次使用client_secret.JSON

参考文献:

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

© www.soinside.com 2019 - 2024. All rights reserved.