在Python中,是否可以对批处理HTTP请求使用每个请求的“指数退避”?

2024-10-01 10:11:50 发布

您现在位置:Python中文网/ 问答频道 /正文

学生们在这里添加了一个我编写的课堂脚本。在

students = getStudents('Year10', '10A')  # VAR

for student in students:
    newStudent = {
        # Student Identifier
        'userId': student
    }
    batch1_1.add(service.courses().students().create(courseId=arCourseId, body=newStudent))
    batch1_1.add(service.courses().students().create(courseId=ciCourseId, body=newStudent))
    batch1_1.add(service.courses().students().create(courseId=dtCourseId, body=newStudent))
    batch1_1.add(service.courses().students().create(courseId=drCourseId, body=newStudent))
    batch1_1.add(service.courses().students().create(courseId=enCourseId, body=newStudent))
    batch1_2.add(service.courses().students().create(courseId=geCourseId, body=newStudent))
    batch1_2.add(service.courses().students().create(courseId=hiCourseId, body=newStudent))
    batch1_2.add(service.courses().students().create(courseId=icCourseId, body=newStudent))
    batch1_2.add(service.courses().students().create(courseId=laCourseId, body=newStudent))
    batch1_2.add(service.courses().students().create(courseId=maCourseId, body=newStudent))
    batch1_3.add(service.courses().students().create(courseId=muCourseId, body=newStudent))
    batch1_3.add(service.courses().students().create(courseId=peCourseId, body=newStudent))
    batch1_3.add(service.courses().students().create(courseId=reCourseId, body=newStudent))
    batch1_3.add(service.courses().students().create(courseId=scCourseId, body=newStudent))
batch1_1.execute()
time.sleep(1)
batch1_2.execute()
time.sleep(1)
batch1_3.execute()
time.sleep(1)

确实有效,但有时个别请求会返回:

“请求https://classroom.googleapis.com/v1/courses/[COURSEID]/students时出现HttpError 500?alt=json返回“内部错误”

对于这些单独的请求,我想编写代码,以便它在收到5xx错误时重试单个失败的请求。但我不确定如何实现这一点。在

目前,如果只有一个学生没有上过课,我就不得不重新运行整个脚本,这当然是浪费资源。在


Tags: 脚本addexecutetimecreateservicebodysleep
1条回答
网友
1楼 · 发布于 2024-10-01 10:11:50

创建批处理时,可以提供一个回调函数,该函数将为添加到批处理中的每个请求调用。在

回调需要三个参数:

  • request_id:您决定标识要添加到批处理中的请求的id(在调用批处理的add()方法时传递它)
  • response:对api进行的单个调用的响应
  • exception:如果批处理的请求出错,则为异常对象

下面是一些伪代码来解释逻辑。在

# sample callback function
def my_batch_callback(request_id, response, exception):
    if exception is not None:
        # Do something with the exception
        print(exception)
    else:
        # Do something with the response
        print("Request is successful: {}".format(response))
    pass

# creation of batch passing in the call back
batch = service.new_batch_http_request(callback=my_batch_callback)

# addition to batch with a specific id
batch.add(service.object().insert(name="test-1", request_id="id-1"))
batch.add(service.object().insert(name="test-2", request_id="id-2"))
batch.add(service.object().insert(name="test-3", request_id="id-3"))

使用回调,您可以使用它们的id保存所有错误的请求,然后稍后重试。有不同的方法来实现这一点:您可以使用一个简单的列表,并在运行批处理之后对其进行检查;或者,您可以创建一个专用的类,并利用它提供的持久性。在

我建议你也看看官方文件here。在

相关问题 更多 >