首页 > 解决方案 > Python“请求”与“urllib3”到 AWS API Gateway

问题描述

我正在编写一个调用 AWS API Gateway 来访问 dynamoDB 的 python 程序。

当我使用 python "requests" 时一切正常: r = requests.post("https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries", data={ 'logbookTimestamp': 时间戳,'Name': "Fred"})

现在为了将其作为 lambda 函数运行,我想使用“urllib3”而不是“requests”,因为 urllib3 默认包含在 lambda 的 python 中。所以现在我正在尝试对 urllib3 做同样的事情,但无法让它工作。我在这里阅读了 urllib3 用户指南(https://urllib3.readthedocs.io/en/latest/user-guide.html#json),它说我需要在发送 JSON 数据之前对其进行编码,所以我已经完成了这个:

http = urllib3.PoolManager()
fields = {'logbookTimestamp': timestamp, 'Name': "Fred"}
encoded_fields = json.dumps(fields).encode('utf-8')
link = "https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries"
r = http.request('POST',
                 link,
                 body=encoded_fields,
                 headers={'Content-Type': 'application/json'}
                 )

当我在 CloudWatch 中查看两者的输出时,我发现数据的格式不同。

有请求:(c084a37e-43d8-464a-9dcf-e40c28922ece) 转换前的方法请求正文:logbookTimestamp=2020%3A12%3A15%3A20%3A11%3A02&Name=Fred

使用 urllib3: (9b8d84e9-2403-462c-b25f-945a927d1e66) 转换前的方法请求正文: { "logbookTimestamp": "2020:12:15:21:31:21", "Name": "Fred" }

并返回以下内容: (9b8d84e9-2403-462c-b25f-945a927d1e66) 转换前的端点响应正文:{ "statusCode": 500, "headers": { "Content-Type": "text/html; charset=utf-8 ", "Content-Length": "290" }, "body": "\n500 内部服务器错误\n

内部服务器错误

\n

服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。

\n" } (9b8d84e9-2403-462c-b25f-945a927d1e66) 转换前的端点响应正文:{"statusCode": 500, "headers": {"Content-Type": "text/html; charset=utf-8", "内容长度": "290"}

我不知道如何以“urllib3”格式获取数据,这些数据将像“请求”一样被接受。有什么想法吗?谢谢!

标签: pythonamazon-web-servicesaws-api-gateway

解决方案


如果您发布您的 json datarequests它将像 html 表单一样提交:

"Content-Type":["application/x-www-form-urlencoded"]

如果你想它去 as json,你应该使用

requests.post("https://xxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/log-entries", json={'logbookTimestamp': timestamp, 'Name': "Fred"})

提交数据为:

"Content-Type":["application/json"]

推荐阅读