适用于 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...