我已经看过关于此主题的其他问题,它似乎不符合我的错误。运行Google Sheets APIv4
时,我得到的错误:上线service.spreadsheets().values().get(spreadsheetId=key, range=ranges).execute()
HttpAccessTokenRefreshError:invalid_grant ...一小时限制刷新令牌
此错误只是偶尔弹出发生
raise HttpAccessTokenRefreshError(error_msg, status=resp.status) HttpAccessTokenRefreshError: invalid_grant
错误。如果我什么都不做,只需再次运行代码。这将再次带我通过认证流程的过程,我也得到
Authentication successful. Storing credentials to C:\Users\jason\.credentials\sheets.googleapis.com-python-quickstart.json
在这之后,我可以到同HttpAccessTokenRefreshError: invalid_grant
再次弹出运行了一段时间的任何代码,我不得不再次重新验证。
我该如何预防?
我使用的代码是developers.google.com/sheets/api/quickstart/python。
我试着使用ntp
同步的时间与以下
import time
import os
try:
import ntplib
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
os.system('date ' + time.strftime('%m%d%H%M%Y.%S',time.localtime(response.tx_time)))
except:
print('Could not sync with time server.')
print('Done.')
但得到:我输入当前日期后
The system cannot accept the date entered.
Enter the new data: (mm-dd-yy)
,什么都不会发生。
当我运行超过1小时的代码完成代码时,也会出现此问题。在刷新令牌上。它总是炸弹。
现在我在想,授予的令牌只能持续一个小时并刷新,它总是炸弹。
我已经发布的代码,用于连接:
class APIv4:
def __init__(self):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
self.service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
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.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'sheets.googleapis.com-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
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
如果您在使用OAuth时遇到问题,请尝试使用API密钥,因为此OAuth都是[受支持的API凭证类型](https://developers.google.com/sheets/api/guides/authorizing#APIKey )。在获得API密钥后,应用程序可以将查询参数'key = yourAPIKey'附加到所有请求URL。 –
@Rebot先生您可以给我一些关于如何设置的示例代码吗?我不明白服务构建以及它如何与Google表APIv4一起使用。我跟随您的链接从凭据中获取我的控制台中的API密钥。我不确定这是否适用于我,因为我的数据不公开。它表示它不访问任何私人用户数据。 – jason
@ Mr.Rebot“尝试使用API密钥,因为这和OAuth都是由Sheets API支持的凭证类型。”是不正确的。只有电子表格是公开的,API密钥才会有效。 – pinoyyid