繁体   English   中英

如何使用Google API客户端创建Python代码

[英]How to Create Python Code with Google API Client

我下面有提供给我的代码,用于列出特定项目的Google Cloud Service帐户。

import os
from googleapiclient import discovery
from gcp import get_key

"""gets all Service Accounts from the Service Account page"""

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

service = discovery.build('iam', 'v1')

project_id = 'projects/<google cloud project>'

request = service.projects().serviceAccounts().list(name=project_id)
response = request.execute()

accounts = response['accounts']

for account in accounts:
    print(account['email'])

这段代码可以正常工作,并在我需要时打印帐户。 我想找出的是:

我在哪里可以看到如何构造这样的代码? 我找到了一个引用了Python API Client的站点,但似乎无法弄清楚如何用它来编写上面的代码。 我可以看到列出服务帐户的方法 ,但是仍然无法提供足够的信息。

还有别的地方我应该去教育自己。 您所拥有的任何信息都将受到赞赏,因此我不会抽出其余的头发。

谢谢,埃里克

您可以使用已安装googleapiclient的ipython类似:

sudo pip install --upgrade google-api-python-client

您可以转到交互式python控制台并执行以下操作:

from googleapiclient import discovery
dir(discovery)
help(discovery)

dir提供对象具有的所有条目-因此:

a = ''
dir(a)

会告诉您可以使用字符串对象做什么。 进行help(a)将为字符串对象提供帮助。 您可以执行北斗:

dir(discovery)#然后例如
帮助(discovery.re)

您可以分步调用脚本,并查看打印结果是什么,做一些研究,做些什么-做%history打印您的会话,并获得可以作为脚本触发的解决方案。

让我与您共享此文档页面 ,其中有有关如何构建脚本(如您共享的脚本)以及每一行代码的含义的详细说明。 它是从ML Engine(而不是IAM)的文档中提取的,但它使用的是相同的Python Google API客户端库,因此只需忽略对ML的引用,其余的内容对您将很有用。

无论如何,这是代码的注释版本,以便您更好地理解它:

# Imports for the Client API Libraries and the key management
import os
from googleapiclient import discovery
from gcp import get_key

# Look for an environment variable containing the credentials for Google Cloud Platform
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_key()

# Build a Python representation of the REST API
service = discovery.build('iam', 'v1')

# Define the Project ID of your project
project_id = 'projects/<google cloud project>'

"""Until this point, the code is general to any API
From this point on, it is specific to the IAM API"""

# Create the request using the appropriate 'serviceAccounts' API
# You can substitute serviceAccounts by any other available API
request = service.projects().serviceAccounts().list(name=project_id)

# Execute the request that was built in the previous step
response = request.execute()

# Process the data from the response obtained with the request execution
accounts = response['accounts']
for account in accounts:
    print(account['email'])

了解了代码的第一部分后,最后几行特定于您使用的API,在本例中为Google IAM API 在此链接中,您可以找到有关可用方法及其作用的详细信息。

然后,您可以遵循共享的Python API客户端库文档 ,以了解如何调用方法。 例如,在您共享的代码中,所使用的方法取决于service ,即API的Python表示形式,然后在最后一个链接中向下钻入方法树,如projects() ,然后是serviceAccounts() ,最后是特定的list()方法,最终以request = service.projects().serviceAccounts().list(name=project_id)

最后,以防万一您对其他可用的API感兴趣,请参阅此页面以获取更多信息。

希望我对您的代码所做的评论有所帮助,并且希望共享的文档可以使您更轻松地理解如何编写类似的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM