Google教室API补丁



在Google教室API中执行courses.courseWork.studentSubmissions.patch方法时,当我尝试更新学生的提交时,将返回403错误。以下是我的代码。

from googleapiclient.discovery import build
from oauth2client import client
import simplejson as json
class Google:
    SCOPE = {
        "profile": {"scope": "profile email", "access_type": "offline"},
        "classroom": {"scope": 'https://www.googleapis.com/auth/classroom.courses.readonly '
                               'https://www.googleapis.com/auth/classroom.rosters.readonly '
                                'https://www.googleapis.com/auth/classroom.profile.emails '
                                'https://www.googleapis.com/auth/classroom.profile.photos ',
                    "access_type": "offline"},
        "classwork":{
            "scope": "https://www.googleapis.com/auth/classroom.coursework.students https://www.googleapis.com/auth/classroom.coursework.me",
            "access_type":"offline"
        },
        "submission":{
            "scope": "https://www.googleapis.com/auth/classroom.coursework.me https://www.googleapis.com/auth/classroom.coursework.students profile email",
            "access_type":"offline"
        }
    }
    ERRORS = {
                "invalid_request":{"code":"invalid_request","msg":"Invalid request. Please Try with login again."},
                "account_used":{"code":"account_used","msg":"Google account is already configured with different PracTutor Account."},
                "assignment_permission_denied":{"code":"assignment_permission_denied","msg":"permission denied"},
                "unknown_error":{"code":"unknown_error","msg":"something went wrong."}
              }
    def __init__(self, code = "", genFor = "profile"):
        if code:
            genFor = genFor if genFor else "profile"
            self.credentials = client.credentials_from_clientsecrets_and_code(pConfig['googleOauthSecretFile'],self.SCOPE[genFor]["scope"], code)
            self.http_auth = self.credentials.authorize(httplib2.Http())
            cred_json = self.credentials.to_json()
            idinfo = json.loads(cred_json)["id_token"]
        else:
            raise ValueError(Google.ERRORS["invalid_request"])
    def getUserInfo(self):
        service = build(serviceName='oauth2', version='v2', http=self.http_auth)
        idinfo = service.userinfo().get().execute()
        return idinfo
    def getClasses(self):
        courses = []
        page_token = None
        service = build('classroom', 'v1', http=self.http_auth)
        while True:
            response = service.courses().list(teacherId="me",pageToken=page_token,
                                              pageSize=100).execute()
            courses.extend(response.get('courses', []))
            page_token = response.get('nextPageToken', None)
            if not page_token:
                break
        return courses
    def getStudent(self,course_id):
        students = []
        page_token = None
        service = build('classroom', 'v1', http=self.http_auth)
        while True:
            response = service.courses().students().list(courseId=course_id, pageToken=page_token,
                                              pageSize=100).execute()
            students.extend(response.get('students', []))
            page_token = response.get('nextPageToken', None)
            if not page_token:
                break
        return students
    def createAssignment(self,course_id,**kwargs):
        service = build('classroom', 'v1', http=self.http_auth)
        date, time = kwargs["dueDate"].split(" ")
        yy,mm,dd = date.split("-")
        h,m,s = time.split(":")
        courseWork = {
            'title': kwargs["title"],
            'description': kwargs["desc"],
            'materials': [
                {'link': { 'url': kwargs["link"] } },
            ],
            'dueDate': {
                "month": mm,
                "year": yy,
                "day": dd
            },
            'dueTime':{
                "hours": h,
                "minutes": m,
                "seconds": s
              },
            'workType': 'ASSIGNMENT',
            'state': 'PUBLISHED',
        }
        courseWork = service.courses().courseWork().create(courseId=course_id, body=courseWork).execute()
        return courseWork
    def submitAssignment(self,**kwargs):
        service = build('classroom', 'v1', http=self.http_auth)
        course_id = kwargs["courseId"]
        courseWorkId = kwargs["courseWorkId"]
        score = kwargs["score"]
        studentSubmission = {
            'assignedGrade': score,
            'draftGrade': score,
            'assignmentSubmission': {
                'attachments': [
                    {
                        'link': {
                            "url": "demo.com",
                            "title": "Assignment1",
                            "thumbnailUrl": "demo.com",
                        }
                    }
                ],
            },
            'state': 'TURNED_IN',
        }
        gCredentials = json.loads(self.credentials.to_json())
        userGId = gCredentials["id_token"]["sub"]
        studentSubmissionsData = service.courses().courseWork().studentSubmissions().list(
            courseId=course_id,
            courseWorkId=courseWorkId,
            userId=userGId).execute()
        studentSubmissionId = studentSubmissionsData["studentSubmissions"][0]["id"]
        courseWorkRes = service.courses().courseWork().studentSubmissions().patch(
                    courseId=course_id,
                    courseWorkId=courseWorkId,
                    id=studentSubmissionId,
                    updateMask='assignedGrade,draftGrade',
                    body=studentSubmission).execute()
        return courseWorkRes

Method Calling     
g = Google()
kwargs = {"courseId":courseId,"courseWorkId":courseWorkId,"score":80}
courseworkResponse = g.submitAssignment(**kwargs)

错误:

https://classroom.googleapis.com/v1/courses/{courses_id}/coursework/{Coursework_id}/studentSubMissions/{suducceUbmissions_id}? 返回的"呼叫者没有许可">

学生的提交包含以下字段分配的级,草稿,附件(链接资源(和状态。

电话是由经过身份验证的学生帐户进行的。开发人员控制台项目已启用Google课堂API,其他打击Google课堂API的电话正常,例如Courses.coursework.coursework.create and Courses.courseworkwork.studentswork.studentsubmissions.list。另外,我正在从相同的开发人员控制台项目中提出课程工作项目的请求。

当我尝试从Google API Explorer尝试时,将返回带有不同消息的同一错误403错误。

{
  "error": {
    "code": 403,
    "message": "@ProjectPermissionDenied The Developer Console project is not permitted to make this request.",
    "status": "PERMISSION_DENIED"
  }
}

任何帮助将不胜感激,谢谢

该错误消息基本上意味着您没有许可去做您正在尝试做的事情。权限与您对用户进行身份验证的范围有关。这是范围的完整列表

方法:courses.coursework.studentsubmis.patch需要以下范围。

授权

需要以下OAuth范围之一:

https://www.googleapis.com/auth/classroom.coursework.students
https://www.googleapis.com/auth/classroom.coursework.me

使用列表并在补丁之前获取

使用列表并在补丁之前获取以确保您具有corect ID。

如果您先有用户预成式列表,然后找到您之后的列表,然后预成式一个获取您可以在获取中更改对象,然后对此进行更新。这样做的方式确保您通过的所有ID都是正确的,并且用户确实可以访问他们试图更新的内容。

最新更新