簡體   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