首页 > 解决方案 > HttpError 503,同时使用 GCP Python API 创建子网

问题描述

大家好,需要您对我使用 python 脚本创建 vpc 和子网时遇到的问题的想法。

创建 vpc 时我的脚本运行良好,但子网创建的下一步失败并出现错误

googleapiclient.errors.HttpError: <HttpError 503 when requesting https://www.googleapis.com/compute/v1/projects/<projectname>/regions/us-east1/subnetworks?alt=json returned "Internal error. Please try again or contact Google Support.

我可以从 UI 和其他 API 页面创建子网。

这是我用于创建子网的脚本代码-

def create_subnet(compute, project, region, classname):

    subnetname = classname
    networkpath = 'projects/<projectname>/global/networks/%s' % (classname)
    ipCidrRange = "10.0.0.0/16"

    config = {
  "name": subnetname,
  "network": networkpath,
  "ipCidrRange": ipCidrRange
}

    print('##### Print Config ##### %s' % (config))

    return compute.subnetworks().insert(
        project=project,
        region=region,
        body=config).execute()
    ```

def main(项目,类名,区域,区域):

compute = googleapiclient.discovery.build('compute', 'v1')

print('Creating vpc')

operation = create_vpc(compute, project, classname)

print('Creating subnet')

operation = create_subnet(compute, project, region, classname)
```

提前感谢您的意见和建议。

标签: pythongoogle-compute-enginegoogle-apis-explorer

解决方案


我找到了这个问题的根本原因。我在没有等待 vpc 创建操作完成的情况下进行子网调用。

创建新函数等待并在 vpc 创建步骤解决问题后调用它。

def wait_for_global_operation(compute, project, operation):
    print('Waiting for operation to finish...')
    while True:
        result = compute.globalOperations().get(
            project=project,
            operation=operation).execute()

        if result['status'] == 'DONE':
            print("done.")
            if 'error' in result:
                raise Exception(result['error'])
            return result

        time.sleep(1)

感谢 Lozano 的评论和反馈。


推荐阅读