authorize() 缺少 1 个必需的位置参数:'http' when 运行 Google Cloud SDK 示例

authorize() missing 1 required positional argument: 'http' when running Google Cloud SDK example

我是 运行 以下代码,是从这个 google 云 sdk 示例中逐行提取的。

import httplib2
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials as creds
crm = discovery.build(
    'cloudresourcemanager', 'v3', http=creds.authorize(httplib2.Http()))

operation = crm.projects().create(
body={
    'project_id': 'test-project',
}).execute() 

我收到以下错误。

Traceback (most recent call last):
  File "/Users/myUsername/src/Chess/gcp/gcp_init.py", line 5, in <module>
    'cloudresourcemanager', 'v3', http=creds.authorize(httplib2.Http()))
TypeError: authorize() missing 1 required positional argument: 'http'

OAuth2Credentials 是一个 class,authorize 是在 class 上定义的方法。因此,它的定义类似于

class OAuth2Credentials:
    ...
    def authorize(self, http):
        ....

(source)

您调用了 class 类型本身的实例方法,而不是先初始化 class,因此您传入的 http 对象在方法内部变成了 self

您应该先实例化一个 OAuth2Credentials 对象。然后,该方法的第一个参数自动成为 class 实例本身,您传入的 http 参数将被正确解释。

import httplib2
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials

creds = OAuth2Credentials(...) # refer to the documentation on how to properly initialize this class
crm = discovery.build(
    'cloudresourcemanager', 'v3', http=creds.authorize(httplib2.Http()))

operation = crm.projects().create(
body={
    'project_id': 'test-project',
}).execute() 

在相关说明中,oauth2clientdeprecated,您应该迁移到他们推荐的较新的库之一。