首页 > 解决方案 > 从 GoogleClassroomApi [403] Python 中检索 ClassWork

问题描述

我正在尝试从 Google Classroom API 检索每门课程的课业。我已成功获得所有课程,但我被困在课程作业上:<HttpError 403 when requesting https://classroom.googleapis.com/v1/ course/167997334462/courseWork?alt=json返回“请求的身份验证范围不足。”>

这是我正在使用的代码:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students.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.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                r"\test\credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # Call the Classroom API
    course_work_results = service.courses().courseWork().list(courseId="167997334462").execute()
    
    [...]

if __name__ == '__main__':
    main()

我已经使用管理员帐户生成了凭据;我也尝试了几个不同的范围,但同样的错误。

你们能帮我吗?

我正在使用 Python 3.9。

谢谢,亚历山德鲁

标签: pythongoogle-classroom

解决方案


  • 由于您正在使用范围

    https://www.googleapis.com/auth/classroom.coursework.students.readonly,

    我假设你是学生。

  • 学生只能访问他们被接受课程参与者的课程的课程作业。

  • 尝试检索另一门课程的课程作业将导致 403 错误。

  • 如果您不是学生,而是您的 Google Workspace 域的管理员,则应使用更广泛的范围,例如 https://www.googleapis.com/auth/classroom.coursework.me.readonly.

  • 请注意,更改源代码中的范围后,您需要删除令牌文件以触发新的身份验证流程。


推荐阅读