適用於 Python 的 Cloud Resource Manager API Client 的新專案

把它們放在一起……

如果你按照上面的例子,你應該在一個名為 my_project_folder 的目錄中,它希望包含一個名為 venv 的子目錄。

確保你的 virtualenv 已啟用。

所有程式碼都可以放在一個檔案中,我們稱之為 create_project.py

my_project_folder 中建立檔案 create_project.py

import json
import time

from apiclient.discovery import build
from oauth2client.client import GoogleCredentials

SERVICE_NAME = "cloudresourcemanager"
SERVICE_VERSION = "v1"

# Don't forget to replace YOUR-PROJECT-ID with your choice of Project ID
# Even though the code deletes the Project, change this value each time
PROJECT_ID = "YOUR-PROJECT-ID"

credentials = GoogleCredentials.get_application_default()

service = build(
    SERVICE_NAME,
    SERVICE_VERSION,
    credentials=credentials)

operation1 = service.projects().create(
    body={
        "project_id": PROJECT_ID
    }
).execute()

print(json.dumps(
    operation1,
    sort_keys=True,
    indent=3))

name = operation1["name"]
while True:
    operation2 = service.operations().get(
        name=name
    ).execute()
    print(json.dumps(
        operation2,
        sort_keys=True,
        indent=3))
    if "done" in operation2:
        if (operation2["done"]):
            break
    time.sleep(1)

raw_input("Press Enter to delete the Project...")

operation3 = service.projects().delete(
    projectId=PROJECT_ID
).execute()

儲存檔案,並從命令提示符下鍵入:

python create_project.py

輸出應類似於:

{
   "metadata": {
      "@type": "type.googleapis.com/google.cloudresourcemanager.v1.ProjectCreationStatus", 
      "createTime": "2017-12-31T00:00:00.000Z"
   }, 
   "name": "operations/pc.1234567890123456789"
}
...
{
   "done": true, 
   "metadata": {
      "@type": "type.googleapis.com/google.cloudresourcemanager.v1.ProjectCreationStatus", 
      "createTime": "2017-12-31T00:00:00.000Z" 
      "gettable": true, 
      "ready": true
   }, 
   "name": "operations/pc.1234567890123456789", 
   "response": {
      "@type": "type.googleapis.com/google.cloudresourcemanager.v1.Project", 
      "createTime": "2017-12-31T00:00:00.000Z", 
      "lifecycleState": "ACTIVE", 
      "projectId": "your-project-id", 
      "projectNumber": "123456789012"
   }
}
...
Press Enter to delete the Project...