使用Python访问Google API:刷新错误'无效授予'几天首次设置后突然出现
在过去的10天内,使用Python 3并使用google_auth_oauthlib
和googleapiclient
packages,我已经能够创建Google表(使用Python代码)并进行基本的写入/读取值到任何单元。我通过在YouTube上浏览随机视频来实现这一目标。
突然,今天晚上,代码停止处理以下错误:
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})
我是Google API的新手,并且不知道为什么会发生这种情况。我需要在Console.cloud.google.com中的帐户中“重置”某些内容来避免这种情况?
以下是以前使用正常工作的代码,但现在没有:
import os
from Google import Create_Service
spreadsheet_id= '1F8mAvHWqHL_3JHuKnv9Fy9vm2_Zm2tR13DNKj9oNxzU'
FOLDER_PATH = r'C:\Users\Owner'
CLIENT_SECRET_FILE = os.path.join(FOLDER_PATH, 'Client_Secret2.json')
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME, API_VERSION, SCOPES)
service.spreadsheets().values().clear(
spreadsheetId=spreadsheet_id,
range='A1:AA1000',
body={}
).execute()
以下是google.py
的代码,其中具有create_service
:
import pickle
import os
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request
def Create_Service(client_secret_file, api_name, api_version, *scopes):
print(client_secret_file, api_name, api_version, scopes, sep='-')
CLIENT_SECRET_FILE = client_secret_file
API_SERVICE_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
print(SCOPES)
cred = None
pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
# print(pickle_file)
if os.path.exists(pickle_file):
with open(pickle_file, 'rb') as token:
cred = pickle.load(token)
if not cred or not cred.valid:
if cred and cred.expired and cred.refresh_token:
cred.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
cred = flow.run_local_server()
with open(pickle_file, 'wb') as token:
pickle.dump(cred, token)
try:
service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
print(API_SERVICE_NAME, 'service created successfully')
return service
except Exception as e:
print('Unable to connect.')
print(e)
return None
def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
return dt
这是我Console的照片.cloud.google.com
:
Within last 10days, with python 3 and by using the google_auth_oauthlib
and googleapiclient
packages, I have been able to create Google Sheet (using python code) and do basic write/read values to any cell. I accomplished this by going through random videos on Youtube.
Suddenly today evening, the code stopped working with the following error:
google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})
I am new to Google API and have no clue why this is happening. Is there something I need to 'reset' in my account in console.cloud.google.com to avoid this?
Following is the code which used to work fine before, but doesnt now:
import os
from Google import Create_Service
spreadsheet_id= '1F8mAvHWqHL_3JHuKnv9Fy9vm2_Zm2tR13DNKj9oNxzU'
FOLDER_PATH = r'C:\Users\Owner'
CLIENT_SECRET_FILE = os.path.join(FOLDER_PATH, 'Client_Secret2.json')
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME, API_VERSION, SCOPES)
service.spreadsheets().values().clear(
spreadsheetId=spreadsheet_id,
range='A1:AA1000',
body={}
).execute()
Here is code for Google.py
which has Create_Service
:
import pickle
import os
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request
def Create_Service(client_secret_file, api_name, api_version, *scopes):
print(client_secret_file, api_name, api_version, scopes, sep='-')
CLIENT_SECRET_FILE = client_secret_file
API_SERVICE_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
print(SCOPES)
cred = None
pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
# print(pickle_file)
if os.path.exists(pickle_file):
with open(pickle_file, 'rb') as token:
cred = pickle.load(token)
if not cred or not cred.valid:
if cred and cred.expired and cred.refresh_token:
cred.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
cred = flow.run_local_server()
with open(pickle_file, 'wb') as token:
pickle.dump(cred, token)
try:
service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
print(API_SERVICE_NAME, 'service created successfully')
return service
except Exception as e:
print('Unable to connect.')
print(e)
return None
def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
return dt
Here is the photo from my console.cloud.google.com
:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要清楚。这与您的凭据文件无关。您的凭据文件不受此错误的影响。
意味着您的应用程序不再可以访问用户帐户。要么您使用的访问令牌已过期,因此您尚未请求Off Line访问权限,因此请勿具有刷新令牌。或刷新令牌已被撤销。
撤销刷新令牌的速度。
以上所有解决方案是再次请求用户访问。如果您正在关注 people quicy quick quick python 。删除“ token.json”,它将导致您的应用再次请求访问。
刷新令牌 expiration
To be clear. This has nothing to do with your credentials file. Your credentials file is unaffected by this error.
Means that your app not longer has access to the users account. Either the access token you are using has expired and you have not requested off line access so do not have a refresh token. Or the refresh token has been revoked.
Cauess for refresh token revoked.
Solution to all of the above is to request access of the user again. If you are following the People quickstart python. Delete 'token.json' it will cause your app to request access again.
Refresh token expiration
我通过删除
.pickle
文件来解决问题,我的Python文件夹中的文件。重新运行我的代码自我生成的新.pickle
文件,并且代码现在运行!I resolved the issue by deleting the
.pickle
file I had in my python folder. Re-running my code self-generated a new.pickle
file and the code runs now!