使用Python访问Google API:刷新错误'无效授予'几天首次设置后突然出现

发布于 2025-01-23 17:20:45 字数 2993 浏览 5 评论 0原文

在过去的10天内,使用Python 3并使用google_auth_oauthlibgoogleapiclient 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.pywhich 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 :

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2025-01-30 17:20:46

要清楚。这与您的凭据文件无关。您的凭据文件不受此错误的影响。

'令牌已过期或撤销。'

意味着您的应用程序不再可以访问用户帐户。要么您使用的访问令牌已过期,因此您尚未请求Off Line访问权限,因此请勿具有刷新令牌。或刷新令牌已被撤销。

撤销刷新令牌的速度。

  • 用户通过其Google帐户撤销了您的访问权限。
  • 用户已授权您的应用程序更多的50次,您没有存储您的应用程序的最新刷新令牌
  • 仍设置为在Google Developer Console中进行测试,因为它在7天后将到期。

以上所有解决方案是再次请求用户访问。如果您正在关注 people quicy quick quick python 。删除“ token.json”,它将导致您的应用再次请求访问。

刷新令牌 expiration

与外部用户类型配置的OAuth同意屏幕和“测试”的发布状态的Google Cloud Platform项目在7天内发行了刷新令牌。

To be clear. This has nothing to do with your credentials file. Your credentials file is unaffected by this error.

'Token has been expired or revoked.'

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.

  • the user has revoked your access via their google account.
  • the user has authorized your app more then 50 times and you are not storing the most recent refresh token
  • Your app is still set to testing in google developer console and there for it will expire after seven days.

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

A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.

enter image description here

剩余の解释 2025-01-30 17:20:46

我通过删除.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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文