我正在尝试创建一个python函数,该函数将启用GCP项目所需的Service API。我相信该API调用将转到“ serviceusage” API,并使用“ services.enable”或“ services.batchEnable”方法。我不知道如何正确地构造查询。
https://cloud.google.com/service-usage/docs/reference/rest/v1/services/enable
我已经能够使用GCP Python客户端库来自动执行大多数用于项目创建的功能,但是不能做到这一点。我直接使用了GCP文档中的代码,但是这种特殊方法很少使用
from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
project = 'projects/964030760997' # TODO: Update placeholder value.
service = discovery.build('serviceusage', 'v1', credentials=credentials)
request = service.projects().services.list(project=project)
response = request.execute()
pprint(service)
这是我得到的答复:
Traceback (most recent call last):
File "enable_apis.py", line 29, in <module>
request = service.services().services.list(project=project)
AttributeError: 'Resource' object has no attribute 'services'
答案 0 :(得分:1)
您引用了错误的文档。这是Service Usage API的链接:
这是我写的一个例子。注意。该代码不处理nextPageToken
,因此仅输出前50个服务。将代码添加到循环中。
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
project = 'projects/myproject'
service = discovery.build('serviceusage', 'v1', credentials=credentials)
request = service.services().list(parent=project)
response = ''
try:
response = request.execute()
except Exception as e:
print(e)
exit(1)
# FIX - This code does not process the nextPageToken
# next = response.get('nextPageToken')
services = response.get('services')
for index in range(len(services)):
item = services[index]
name = item['config']['name']
state = item['state']
print("%-50s %s" % (name, state))
此代码的输出类似于以下内容:
abusiveexperiencereport.googleapis.com DISABLED
acceleratedmobilepageurl.googleapis.com DISABLED
accessapproval.googleapis.com DISABLED
accesscontextmanager.googleapis.com DISABLED
actions.googleapis.com DISABLED
adexchangebuyer-json.googleapis.com DISABLED
adexchangebuyer.googleapis.com DISABLED
adexchangeseller.googleapis.com DISABLED
adexperiencereport.googleapis.com DISABLED
admin.googleapis.com ENABLED
adsense.googleapis.com DISABLED