我已經看過關於此主題的其他問題,它似乎不符合我的錯誤。運行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