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

217m

我遵循了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.comJSON文件的开头为:

"_module": "oauth2client.client".

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

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

  • 我想不,因为我可以在没有client_secret.JSON文件的情况下使API正常工作
Tanaike

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

流 :

  1. client_secret.JSON从API控制台下载
    • client_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和范围检索授权代码,然后使用client_idclient_secret授权代码检索访问令牌和刷新令牌redirect_uris
  • 在首次运行快速入门之后,刷新令牌将从中检索访问令牌sheets.googleapis.com-python-quickstart.JSON这样,就不需要使用浏览器检索授权代码。因此,当存在时sheets.googleapis.com-python-quickstart.JSONclient_secret.JSON则不需要。
    • 我认为这为您的问题2带来了答案。
  • 但是,如果您想更改的范围和/或凭据client_secret.JSON,则需要使用浏览器进行授权过程并检索授权代码。为此,您必须删除sheets.googleapis.com-python-quickstart.JSON并再次授权。那时,在Quickstart上client_secret.JSON再次使用。

参考文献:

如果这对您没有用,对不起。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章