python - 当我在谷歌教室尝试批量注册参考代码时出现“未定义变量: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
来人帮帮我。
解决方案
让我们深入研究文档以找到答案!
该错误出现在对批处理对象的执行函数的调用中。那么什么样的对象是批处理呢?
它是从对服务对象的 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 模块的一部分,位于
错误来自对批处理对象的执行函数的调用,我们猜测它是一个 BatchHttpRequest。幸运的是,BatchHttpRequest 有一个执行函数,并且该执行函数接受一个 http 参数。执行函数的文档说 http 参数可以省略,但如果提供,它应该是一个 httplib2.Http。
参考代码传递了一个称为http
参数的对象,也称为http
,但不费心构造它。这就是编译器抱怨它未定义的原因。
所以要编译代码,你应该可以省略http=http
参数。然后也许它会运行,也许它不会。如果没有,您将必须弄清楚如何使用 httplib2 库构建适当的 Http 对象,文档位于:
https://httplib2.readthedocs.io/en/latest/libhttplib2.html#http-objects
推荐阅读
- python - 循环和列表 - Python
- windows - How to escape & ampersand in Custom protocol handler in Windows
- java - How to draw 10000 circles in Random locations using JavaFX?
- angular - “无效的规则结果:类 Promise 的实例”是如何找到解决问题的方法,我正在以角度“ng new sample-angular”在新应用程序上创建
- vue.js - 如何在 vue.js 文件中注释 vuetify 代码
- php - import dlib ImportError:在 Ubuntu 18.04 中没有名为 dlib 的模块
- excel - 从子到函数
- javascript - Confused why my regex expression isn't working?
- watson-assistant - How to save user response in DB or External System in watson assistant
- javascript - 在 jquery 中使用 window.location.href 时如何在同一页面上重定向?