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

时间:2017-12-30 03:53:40

标签: python json api credentials google-sheets-api

我按照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​​。

1 个答案:

答案 0 :(得分:1)

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

流程:

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

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

    参考文献:

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