AWS Lambda 中的 Python:来自 botocore.vendored 的“请求”已弃用,但“请求”不可用

新手上路,请多包涵

我有一个 AWS Lambda 函数的 Python 脚本,它向另一个端点发出 HTTP POST 请求。由于 Python 的 urllib2.request https://docs.python.org/2/library/urllib2.html 只能处理标准格式的数据 application/x-www-form-urlencoded 格式,我想发布 JSON 数据,我使用了 Requests 库, https://pypi.org/project/requests/2.7.0/

该 Requests 库在 Python 运行时环境中的 AWS Lambda 不可用,因此必须通过 from botocore.vendored import requests 导入。到目前为止,一切都很好。

今天,我收到一个弃用警告:

 DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'.
This is not a public API in botocore and will be removed in the future.
Additionally, this version of requests is out of date. We recommend you install the
requests package, 'import requests' directly, and use the requests.post() function instead.

AWS 的这篇博文中也提到了这一点: https ://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/。

不幸的是,将 from botocore.vendored import requests 更改为 import requests 会导致以下错误:

 No module named 'requests'

为什么 requests 不适用于 AWS Lambda 的 Python 运行时?我该如何使用/导入它?

原文由 Jochem Schulenklopper 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 804
2 个回答

如果您使用的是 无服务器框架

指定插件 serverless.yml

 plugins:
- serverless-python-requirements

在根目录创建文件 requirements.txt

要求.txt

 requests==2.22.0

这将安装提到的请求和包。

原文由 Yugandhar Chaudhari 发布,翻译遵循 CC BY-SA 4.0 许可协议

我使用 urllib3 库成功发送了 HTTP POST 请求,该库可在 AWS Lambda 获得,无需额外的安装说明。

 import urllib3

http = urllib3.PoolManager()

response = http.request('POST',
                        url,
                        body = json.dumps(some_data_structure),
                        headers = {'Content-Type': 'application/json'},
                        retries = False)

原文由 Jochem Schulenklopper 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题