最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - 403 Forbidden error when using Google Classroom Studentsubmission.patch - Stack Overflow

programmeradmin2浏览0评论
def grade_submissions(service, course_id, coursework_id, submissions, grade):
    for submission in submissions:
        submission_id = submission.get('id')  # Get the submission ID
        try:
            # Update the submission with the assigned grade
            response = service.courses().courseWork().studentSubmissions().patch(
                courseId=course_id,
                courseWorkId=coursework_id,
                id=submission_id,
                updateMask='assignedGrade',
                body={'assignedGrade': grade}
            ).execute()
            print(f"Graded submission ID: {submission_id} with grade: {grade}")
        except HttpError as error:
            print(f"An error occurred while grading submission ID {submission_id}: {error}")



I'm getting a permission denied error, but it's weird because I'm able to call the studentSubmissions().list endpoint just fine. Please help me figure out where I'm going wrong.

Here is my cred set up. I've tried updating the token json, but nothing seems to work

SCOPES = [
    ".courses",  # Access to Classroom courses
    ".coursework.students",  # Access to student coursework
    ".coursework.me",  # Access to user's coursework
    ".readonly"  # Read-only access to Google Drive
]

"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None  # Initialize credentials variable to None

# Check if the token.json file exists to load existing credentials
# 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("new_token.json"):
    creds = Credentials.from_authorized_user_file("new_token.json", SCOPES)  # Load credentials from file

# 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())  # Refresh the credentials if they are expired
    else:
        # Initiate the OAuth2 flow using client secrets file
        flow = InstalledAppFlow.from_client_secrets_file(
            "credentials.json", SCOPES
        )
        creds = flow.run_local_server(port=0)  # Run local server for user authentication
    # Save the credentials for the next run
    with open("new_token.json", "w") as token:
        token.write(creds.to_json())  # Write the credentials to token.json

try:
    # Build the Classroom API service object
    service = build("classroom", "v1", credentials=creds)
def grade_submissions(service, course_id, coursework_id, submissions, grade):
    for submission in submissions:
        submission_id = submission.get('id')  # Get the submission ID
        try:
            # Update the submission with the assigned grade
            response = service.courses().courseWork().studentSubmissions().patch(
                courseId=course_id,
                courseWorkId=coursework_id,
                id=submission_id,
                updateMask='assignedGrade',
                body={'assignedGrade': grade}
            ).execute()
            print(f"Graded submission ID: {submission_id} with grade: {grade}")
        except HttpError as error:
            print(f"An error occurred while grading submission ID {submission_id}: {error}")



I'm getting a permission denied error, but it's weird because I'm able to call the studentSubmissions().list endpoint just fine. Please help me figure out where I'm going wrong.

Here is my cred set up. I've tried updating the token json, but nothing seems to work

SCOPES = [
    "https://www.googleapis/auth/classroom.courses",  # Access to Classroom courses
    "https://www.googleapis/auth/classroom.coursework.students",  # Access to student coursework
    "https://www.googleapis/auth/classroom.coursework.me",  # Access to user's coursework
    "https://www.googleapis/auth/drive.readonly"  # Read-only access to Google Drive
]

"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None  # Initialize credentials variable to None

# Check if the token.json file exists to load existing credentials
# 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("new_token.json"):
    creds = Credentials.from_authorized_user_file("new_token.json", SCOPES)  # Load credentials from file

# 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())  # Refresh the credentials if they are expired
    else:
        # Initiate the OAuth2 flow using client secrets file
        flow = InstalledAppFlow.from_client_secrets_file(
            "credentials.json", SCOPES
        )
        creds = flow.run_local_server(port=0)  # Run local server for user authentication
    # Save the credentials for the next run
    with open("new_token.json", "w") as token:
        token.write(creds.to_json())  # Write the credentials to token.json

try:
    # Build the Classroom API service object
    service = build("classroom", "v1", credentials=creds)
Share Improve this question asked Mar 3 at 5:03 davidocodesdavidocodes 1651 gold badge1 silver badge10 bronze badges 2
  • Just to clarify, are you calling the script as a teacher? – David Commented Mar 3 at 15:04
  • @David Yes, I am the teacher in the course. – davidocodes Commented Mar 3 at 18:36
Add a comment  | 

1 Answer 1

Reset to default 1

The issue was that the assignment was created by the google classroom UI rather than my python code. Google doesn't allow you to modify the grade of any assignment that isn't directly associated with you. If you run this code and get a permission error, you won't be able to update the grade.

coursework = service.courses().courseWork().get(
    courseId=course_id, 
    id=coursework_id
).execute()

if not coursework.get('associatedWithDeveloper'):
    raise PermissionError("Resource owned by Google's internal project")
else:
    print("This is associated with you!")

发布评论

评论列表(0)

  1. 暂无评论