AWS lambda:Python 类型错误 concat str to bytes

AWS lambda: Python Type error concat str to bytes

我在发出 REST post 请求的 AWS lambda 函数中有以下代码。 该代码在 2.7 中有效,但在 3.7 中抛出错误。

错误在请求的 header 部分。但我不清楚如何修复它。

代码片段如下:

    DOMAIN = 'xxx-yyy.com'
    TOKEN = 'xdfbvgsded5e9fb99a'
    JOB = 1
    build_url = f'https://{DOMAIN}/api/2.0/jobs/run-now'
    response = requests.post(build_url,headers={'Authorization': b"Basic " + base64.standard_b64encode(b"token:" + TOKEN)}, json={"job_id": JOB})
    # response = requests.get("http://www.google.com")
    if response.status_code == 200:
        print("Request Submitted")
    else:
        print("Error launching cluster")```

Error message

```{
  "errorMessage": "can't concat str to bytes",
  "errorType": "TypeError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 11, in lambda_handler\n    headers = {'Authorization': b\"Basic \" + base64.standard_b64encode(b\"token:\" + TOKEN)}\n"```

  ]
} ```



您正在尝试将 str (TOKEN) 连接到 bytes 变量

要修复 TOKEN 一个 bytes 变量:

TOKEN = b'xdfbvgsded5e9fb99a'
authorization = b"Basic " + base64.standard_b64encode(b"token:" + TOKEN)

我认为 Authorization header 需要一个 str,但是因为你有一个字节,这里有两个选项。

作为字节:

headers={'Authorization': authorization}

作为海峡:

headers={'Authorization': authorization.decode("utf-8")}