Google API Python|ValueError:授权用户信息不是预期的格式,缺少字段client_secret、client_id、refresh_token

amrnrhlw  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(173)
Traceback (most recent call last):
    creds = Credentials.from_authorized_user_file('credent.json', SCOPES)
  File "C:\Users\WINDOWS\AppData\Local\Programs\Python\Python310\lib\site-packages\google\oauth2\credentials.py", line 440, in from_authorized_user_file
    return cls.from_authorized_user_info(data, scopes)
  File "C:\Users\WINDOWS\AppData\Local\Programs\Python\Python310\lib\site-packages\google\oauth2\credentials.py", line 390, in from_authorized_user_info
    raise ValueError(
ValueError: Authorized user info was not in the expected format, missing fields client_secret, client_id, refresh_token.

我创建了一个OAuth客户端ID,将那里的应用程序类型设置为桌面应用程序,下载了json文件,然后尝试登录(代码如下)并得到一个错误,我输入了文件,它是按照这个顺序(下面的示例),后来我从json中删除了'installed',现在错误是不同的ValueError: Authorized user info was not in the expected format, missing fields refresh_token.

JSON EXAMPLE

{"installed":
    {"client_id": "client_id_my",
    "project_id": "projectname123",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "SECRET",
    "redirect_uris": ["http://localhost"]}
}
import os.path

from google.oauth2.credentials import Credentials
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']

creds = Credentials.from_authorized_user_file('credent.json', SCOPES)
qlckcl4x

qlckcl4x1#

您遇到的错误消息与缺少token.json文件有关。这个文件是使用credentials.json文件自动创建的(在您的示例中,根据您的代码片段,我认为它被称为credent.json)。
因此,与在这部分代码中调用credentials.json文件不同:

SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']

creds = Credentials.from_authorized_user_file('credent.json', SCOPES)

您需要调用在授权流完成后创建的令牌文件。authorization flow是下面示例的这一部分:

creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

一旦代码被创建并存储。您可以像这样创建creds(用于构建服务的凭据):

SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']

creds = Credentials.from_authorized_user_file('token.json', SCOPES)
  • 注意:您可以将凭据文件重命名为credentials.json,也可以将示例代码替换为JSON文件的名称。*

这是一个基于Google文档here的示例代码。
以该样本为基础,它应该是这样的:

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']

def main():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('classroom', 'v1', credentials=creds)

        # Here you will add whatever method you want to use. 

    except HttpError as error:
        print('An error occurred: %s' % error)

if __name__ == '__main__':
    main()

参考:

相关问题