首页 > 解决方案 > GCP Compute Engine Python API 和实例模板不起作用?

问题描述

每次我尝试在 python Compute Engine API 中使用实例模板时,它都会错误地输出 URL。

例如:使用 PyCharm 和 Python 3.9

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

host_project = 'testproject123'
host_zone = 'us-central1-a'

vm_name = host_project+'-api-fetch'
instance_template = 'projects/testproject123/global/instanceTemplates/testproject123-api-1'

compute.instances().insert(project=host_project, zone=host_zone, sourceInstanceTemplate=instance_template).execute()

哪个返回

Error
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "[PATH]main.py", line 14, in <module>
    compute.instances().insert(project=host_project, zone=host_zone, sourceInstanceTemplate=instance_template).execute()
  File "C:\Users\[USER]\AppData\Roaming\Python\Python39\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\[USER]\AppData\Roaming\Python\Python39\site-packages\googleapiclient\http.py", line 935, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://compute.googleapis.com/compute/v1/projects/testproject123/zones/us-central1-a/instances?sourceInstanceTemplate=projects%2Ftestproject123%2Fglobal%2FinstanceTemplates%2Ftestproject123-api-1&alt=json returned "Required field 'resource' not specified". Details: "[{'message': "Required field 'resource' not specified", 'domain': 'global', 'reason': 'required'}]">

知道为什么它不断将“/”转换为 %2 吗?我假设这是导致问题的原因,但我似乎无法追溯或找到简单的修复方法。

标签: pythongoogle-compute-enginegoogle-cloud-instance-template

解决方案


显然,即使在https://googleapis.github.io/google-api-python-client/docs/dyn/compute_v1.instances.html#insert中正文是可选的,仍然需要带有名称的正文。添加它完全解决了这个问题。

%2F 一直作为 URL 编码的斜线正常工作。


推荐阅读