python - 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”格式获取数据,这些数据将像“请求”一样被接受。有什么想法吗?谢谢!
解决方案
如果您发布您的 json data
,requests
它将像 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"]
推荐阅读
- node.js - NODE.JS - 如何使用 bcrypt 检查 Laravel 散列密码?
- angular - 如何将日期从 SpringBoot JPA 传递到 Angular
- c - 通过 rtp 识别 h264 中的 idr 数据包
- sql-server - 如何识别在 SSMS 中包含相同数据的不一致列标题
- assembly - 关于x86 I/O端口地址和IN/OUT指令的问题
- linux - 当您为其提供服务的默认端口号时返回服务名称的脚本
- c++ - 无法通过 lambda 的 const 值返回
- python - 使用 type() 在 python 中填充自定义类对象
- kotlin - 如何赶上动画的结尾
- php - 如何检查括号是否平衡?