0

我能够使用来自此处此处的信息拼凑一个 Python 脚本以与 Google API 库进行交互。下面的代码正在运行,我可以列出特定项目中的所有帐户。见下文:

代码:

import os
from googleapiclient import discovery
from gcp import get_key

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()

service = discovery.build('cloudresourcemanager', 'v1')
project_id = 'test-buckets'

get_iam = {}

request = service.projects().getIamPolicy(resource=project_id, body=get_iam)
response = request.execute()

bindings = response['bindings']

for binding in bindings:
    for member in binding['members']:
        print(member)

输出:

ssh://xxxx@x.x.x.x:22/home/xxxx/venv/bin/python3.4 -u /home/xxxx/scratch.py

serviceAccount:xxxxxxxxxxx-compute@developer.gserviceaccount.com
serviceAccount:xxxxxxxxxxx@xxxxxxxxxxx.iam.gserviceaccount.com
user:xxxx@.xxxxx.com

现在,我试图利用 API 删除不需要的特定帐户(下面的脚本),但是,我似乎无法让 API 工作。我在这里再次使用 Google API 库,但它似乎不起作用。我不确定我做错了什么。非常感谢您提供的任何帮助。

代码:

import os
from pprint import pprint
from googleapiclient import discovery
from gcp import get_key

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()

service = discovery.build('cloudresourcemanager', 'v1')
project_id = 'test-buckets'

service_account = 'projects/xxxxxxx/serviceAccounts/test-delete@test-buckets.iam.gserviceaccount.com'

request = service.projects().delete(name=service_account, body={})
response = request.execute()

pprint(response)

输出:

ssh://xxxx@x.x.x.x:22/home/xxxx/venv/bin/python3.4 -u /home/xxxx/scratch2.py
Traceback (most recent call last):
  File "/home/xxxx/scratch2.py", line 13, in <module>
    request = service.projects().delete(name=service_account, body={})
  File "/home/xxxx/venv/lib/python3.4/site-packages/googleapiclient/discovery.py", line 722, in method
    raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "body"

Process finished with exit code 1
4

2 回答 2

0

也许答案为时已晚,但我认为您的代码中唯一的错误是这行代码:

request = service.projects().delete(name=service_account, body={})

实际上应该是这样的:

request = service.projects().delete(name=service_account)

正如您在共享的错误中看到的那样,TypeError: Got an unexpected keyword argument "body"这里body不接受参数。无论如何,打印响应pprint(response)可能不会输出任何内容,因为对 DELETE 操作的响应没有内容。

于 2018-01-11T09:13:47.327 回答
0

我发现我在构建服务时也使用了错误的 API。以下是更正后的代码:

service = discovery.build('iam', 'v1')
request = service.projects().serviceAccounts().delete(name=project_name)
response = request.execute()
于 2018-01-12T19:24:53.400 回答