python - POST 到 google apis 计算引擎给出 400

标签 python google-api google-compute-engine

我正在构建一个小型 flask 应用程序来处理我正在开发的另一个项目的自动部署。

这涉及使用 googleapis 设置 gcloud 防火墙规则。

我已遵循以下文档。

https://cloud.google.com/compute/docs/reference/latest/firewalls/insert

当我按以下方式进行 POST 调用时。

    headers = {
    'Authorization': 'Bearer {}'.format(access_token)
 }
     name = unique_identifier + "-rule"
     payload = {
          "kind": "compute#firewall",
          "name": name,
          "sourceRanges": [
            "0.0.0.0/0"
          ],
          "sourceTags": [
            unique_identifier
          ],
          "allowed": [
              {
                "IPProtocol": "tcp",
                "ports": [
                 port_number
                ]
              }
            ]
        }
     data = json.dumps(payload)
     r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   data=data, headers=headers)

其中 port_number 和 unique_identifier 是字符串。 access_token 是使用我设置的服务帐户检索的。我确信该 token 是好的,因为我可以使用该 token 对 protected 资源进行 GET 调用。

我使用的是Python 3.5。

对此帖子的回复如下。

{
"error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required field 'resource' not specified"
   }
  ],
  "code": 400,
  "message": "Required field 'resource' not specified"
 }
}

错误消息声称我缺少一个字段,尽管我拥有下面链接中指定的所有必填字段。

https://cloud.google.com/compute/docs/reference/latest/firewalls/insert#request-body

我究竟做错了什么?

最佳答案

想通了。我删除了。

data = json.dumps(payload)

改变了

 r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   data=data, headers=headers)

 r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   json=data, headers=headers)

关于python - POST 到 google apis 计算引擎给出 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752982/

相关文章:

python - 在 Python 中反射(reflect)/检查封闭变量

go - Go 中对 Google API 的无人值守授权

python - 在 django-storages 和 S3 中移动文件而不打开

python - setuptools.setup 的 name 参数值如何影响结果?

javascript - 使用 Javascript 通过 Google 客户端库进行批量请求

google-cloud-storage - Presto 抢占式 GCE 实例

kubernetes - Google Kubernetes群集无法自动缩减

gpu - cos-extensions 安装 gpu 无法在 GCP Compute Engine VM 上下载驱动程序签名

python - Python 中的类继承问题

PHP Google Sheets API - 权限被拒绝