我按照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。这个答案怎么样?我想当您知道用于检索访问令牌和刷新令牌的OAuth2流程时,您可以理解这两个文件的含义。使用OAuth2检索访问令牌和刷新令牌的流程如下。
client_secret.JSON
。
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
和scopes检索授权代码,然后使用授权代码client_id
,client_secret
和redirect_uris
检索访问令牌和刷新令牌。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
。如果这对你没用,我很抱歉。