首页 > 解决方案 > 当我在谷歌教室尝试批量注册参考代码时出现“未定义变量:http”错误

问题描述

我正在尝试测试批量注册以建立谷歌课堂,但我发现了一些编译错误batch.execute(http=**http**)

错误消息是“未定义的变量:http”

这是该代码的最后一部分发生的代码和编译错误。

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)

参考在下面。

https://developers.google.com/classroom/guides/batch#python

来人帮帮我。

标签: pythongoogle-classroom

解决方案


让我们深入研究文档以找到答案!

该错误出现在对批处理对象的执行函数的调用中。那么什么样的对象是批处理呢?

它是从对服务对象的 new_batch_http_request 的调用中返回的。那么服务是一个什么样的对象呢?

它不是在您引用的参考代码中创建的,因此我们必须在文档中翻找其他一些代码service来创建命名的东西。作者可能假设此示例中的服务是同一种对象。

Python 的快速入门页面似乎是一个很好的查看位置,果然,有代码创建了一个名为service该处的对象:

service = build('classroom', 'v1', credentials=creds)

所以我们可以猜测该服务是从构建调用中返回的。那么什么是构建?

它在同一个示例中定义:

from googleapiclient.discovery import build

所以现在我们必须找到 googleapiclient.discovery 的文档。搜索该名称会导致我们:

https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-module.html

在这里,我们看到 build 函数返回了一个 Resource。所以服务是一种资源。

但是当我们查看 Resource 的文档时,它没有函数 new_batch_http_request。这是什么卑鄙的背叛?

“new_batch_http_request” 看起来像一个非常独特的字符串,所以我们可以搜索它。让我们试试 Google Classroom API 网站的搜索框。

它只找到我们开始的批处理请求页面。但它也提供搜索所有 Google Developers 的功能。所以让我们这样做。

然后搜索结果显示,有很多 API 具有此名称的函数,并且它们似乎都创建了 BatchHttpRequest 对象,因此 Resource 的那个可能也是。那么什么是 BatchHttpRequest?让我们再次搜索这个名字!

它被记录为 googleapiclient 包的 http 模块的一部分,位于

https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.BatchHttpRequest-class.html

错误来自对批处理对象的执行函数的调用,我们猜测它是一个 BatchHttpRequest。幸运的是,BatchHttpRequest 有一个执行函数,并且该执行函数接受一个 http 参数。执行函数的文档说 http 参数可以省略,但如果提供,它应该是一个 httplib2.Http。

参考代码传递了一个称为http参数的对象,也称为http,但不费心构造它。这就是编译器抱怨它未定义的原因。

所以要编译代码,你应该可以省略http=http参数。然后也许它会运行,也许它不会。如果没有,您将必须弄清楚如何使用 httplib2 库构建适当的 Http 对象,文档位于:

https://httplib2.readthedocs.io/en/latest/libhttplib2.html#http-objects


推荐阅读