在Google Classroom 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_id} / studentSubmissions / {studentSubmissions_id} ALT = JSON&安培; updateMask = assignedGrade%2CdraftGrade 返回"来电者没有权限">
学生提交的内容包含以下字段:Grade,draftGrade,attachments(链接资源)和州。
通过经过身份验证的学生帐户拨打电话。 Developer Console项目启用了Google Classroom API,其他对Google Classroom API的调用工作正常,例如courses.courseWork.create和courses.courseWork.studentSubmissions.list。此外,我正在从相关/创建课程工作项的同一个开发者控制台项目发出请求。
当我尝试使用Google API资源管理器时,会返回相同的错误403错误和不同的消息。
{
"error": {
"code": 403,
"message": "@ProjectPermissionDenied The Developer Console project is not permitted to make this request.",
"status": "PERMISSION_DENIED"
}
}
任何帮助将不胜感激,谢谢
答案 0 :(得分:0)
该错误消息基本上意味着您无权执行您尝试执行的操作。权限与您对用户进行身份验证的范围有关。这是scopes
的完整列表Method: courses.courseWork.studentSubmis.patch需要以下范围。
<强>授权强>
需要以下OAuth范围之一:
https://www.googleapis.com/auth/classroom.coursework.students
https://www.googleapis.com/auth/classroom.coursework.me
使用列表和补丁前获取
使用list并在补丁之前获取以确保您拥有corect ID。
如果您让用户首先预先形成list,然后找到您所在的那个,那么预先形成get您可以在get中对对象进行更改,然后对其进行更新。这样做可以确保您传递的所有ID都是正确的,并且用户确实可以访问他们尝试更新的内容。