【问题标题】:Google Clasroom Python API Use batch request and get the request backGoogle Classroom Python API 使用批处理请求并取回请求
【发布时间】: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


【解决方案1】:

您对此有回应吗?您如何处理下一页令牌并将它们添加到批处理调用中?

def makeRequestWithExponentialBackoff(analytics):
    for n in range(0, 5):
        try:
            response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
                                                                                    courseWorkId='-', pageSize=100000)
            print(response.get("studentSubmissions", []))
            return assignments.extend(response.get("nextPageToken", []))

        except:
            time.sleep((2 ** n) + random.random())
            continue
    print("There has been an error, the request never succeeded.")


def callback(request_id, response, exception):
    if exception is not None:
        print('Error getting assignments "{0}" for course: "{1}"'.format(request_id, exception))
        makeRequestWithExponentialBackoff(request_id)
    else:
        assignments.extend(response.get("studentSubmissions", []))
        nextPageToken = response.get("nextPageToken", None)
        if nextPageToken:
            iftoken(nextPageToken, request_id)
        else:
            pass


for k, v in filtered.iterrows():
    if count % 1000 == 0:
        submit = batch.execute(http=http)
        batch_count += 1
        print(batch_count)
        time.sleep(30)
        batch_array.append({'batchSent {}'.format(v['id'])})
        batch = None
        batch = service_two.new_batch_http_request(callback=callback)
        response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
                                                                                courseWorkId='-', pageSize=100000)
        batch.add(response, request_id=v['id'])
        array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
        count = 1
    elif count % 1000 != 0 and batch == None:
        batch = service_two.new_batch_http_request(callback=callback)
        response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
                                                                                courseWorkId='-', pageSize=100000)
        batch.add(response, request_id=v['id'])
        array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
        count += 1
    else:
        response = service_two.courses().courseWork().studentSubmissions().list(pageToken=None, courseId=v['id'],
                                                                                courseWorkId='-', pageSize=100000)
        batch.add(response, request_id=v['id'])
        array.append({'email': v['primaryEmail'], 'count': count, 'classid': v['id']})
        count += 1

其中过滤的是教室 ID 的数据框。然而,nextpagetokens 有问题,如何将它们添加到数据框中?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多