我遵循了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:要成功使用Google Sheets API,是否需要这两个JSON文件?
client_secret.JSON
文件的情况下使API正常工作。这个答案怎么样?我认为,当您知道用于检索访问令牌和刷新令牌的OAuth2流程时,就可以理解两个文件的含义。使用OAuth2检索访问令牌和刷新令牌的流程如下。
client_secret.JSON
从API控制台下载。
client_secret.JSON
包括client_id
,client_secret
和redirect_uris
。client_id
从检索授权码client_secret.JSON
。client_id
,client_secret
和redirect_uris
。
sheets.googleapis.com-python-quickstart.JSON
。client_id
和范围检索授权代码,然后使用client_id
,client_secret
和授权代码检索访问令牌和刷新令牌redirect_uris
。sheets.googleapis.com-python-quickstart.JSON
。这样,就不需要使用浏览器检索授权代码。因此,当存在时sheets.googleapis.com-python-quickstart.JSON
,client_secret.JSON
则不需要。
client_secret.JSON
,则需要使用浏览器进行授权过程并检索授权代码。为此,您必须删除sheets.googleapis.com-python-quickstart.JSON
并再次授权。那时,在Quickstart上client_secret.JSON
再次使用。如果这对您没有用,对不起。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句