【发布时间】:2020-05-10 20:51:54
【问题描述】:
我是谷歌教室 api 的新手,几天前才开始。我想使用批处理请求来使代码更快。我的问题是我不知道如何从批处理中取回数据。我尝试在控制台中打印它,但它返回 null。
def get_all_courses(service):
nextpageToken = ""
list_id = []
while nextpageToken is not None:
result = service.courses().list(
pageSize=500,
pageToken=nextpageToken,
fields="nextPageToken,courses(id)"
)
result = result.execute()
lista_curs = result.get("courses")
for curs in lista_curs:
list_id.append(curs.get('id'))
nextpageToken = result.get("nextPageToken")
print("Ther are :" + str(len(list_id)))
return list_id
这是正常的常用代码。如何将请求传递给批处理并返回结果?
batch1 = service.new_batch_http_request()
result = service.courses().list(
pageSize=500,
pageToken=nextpageToken,
fields="nextPageToken,courses(id)"
)
batch1.add(result)
batch1.execute()# how do I get back the result? do I have to call result.execute() again?
这是来自文档的代码:https://developers.google.com/classroom/guides/batch
course_id = '123456'
student_emails = ['alice@example.edu', 'bob@example.edu']
def callback(request_id, response, exception):
if exception is not None:
print 'Error adding user "{0}" to the course course: {1}'.format(
request_id, exception)
else:
print 'User "{0}" added as a student to the course.'.format(
response.get('profile').get('name').get('fullName'))
batch = service.new_batch_http_request(callback=callback)
for student_email in student_emails:
student = {
'userId': student_email
}
request = service.courses().students().create(courseId=course_id,
body=student)
batch.add(request, request_id=student_email)
batch.execute(http=http) # what is http? what can I pass there? what kind of object is that?
提前谢谢你
【问题讨论】:
-
您是否尝试过在变量中设置
batch1.execute()并打印出来? -
ceva = batch1.execute() print(ceva) 没有给我
-
抱歉回复晚了。
execute(http=http)是 here 所记录的序列化 httprequest。那些在回调函数中形成响应的字段呢?他们可以返回您需要的信息吗? -
嗨,没问题。很少有人回复谷歌教室标签。所以谢谢 :)。序列化的httprequest是什么意思?在文档中,该行是这样的
batch.execute(http=http),但代码中从未定义过http。 -
http只是 API 使用的 httplib2 库中的 http 对象。导入时会自动加载,因此无需在代码中定义。
标签: python batch-processing google-classroom