AWS Lambda 上的 Python:不推荐使用来自 botocore.vendored 的 `requests`,但 `requests` 不可用

Joc*_*per 17 python amazon-web-services python-requests aws-lambda

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

该请求库在 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.
Run Code Online (Sandbox Code Playgroud)

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

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

No module named 'requests'
Run Code Online (Sandbox Code Playgroud)

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

Joc*_*per 23

我使用该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)
Run Code Online (Sandbox Code Playgroud)

  • 您在哪个 URL 上收到 403 错误?例如 `curl -X POST <your-URL>` 或 `curl --data "pi:3.14159265" <your-URL>` 不存在该错误?403 意味着服务器理解该请求,但拒绝授权它......因此问题更有可能是您针对该端点的请求而不是“urllib3”库。 (2认同)

Mar*_*ark 6

查看此处的说明:https : //docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-dependencies

您需要做的就是在本地下载请求模块,然后将其包含在您的 Lambda 函数部署包(ZIP 存档)中。

示例(如果您的所有 Lambda 函数由一个 Python 模块 + 请求模块组成):

$ pip install --target ./package requests
$ cd package
$ zip -r9 ${OLDPWD}/function.zip .
$ cd $OLDPWD
$ zip -g function.zip lambda_function.py
$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip
Run Code Online (Sandbox Code Playgroud)


igo*_*rkf 6

回答 2020-06-18

我找到了一种requests在 AWS Lambda 函数中使用的好方法!

打开此链接并找到您的函数正在使用的区域:https :
//github.com/keithrozario/Klayers/tree/master/deployments/python3.8/arns

打开.csv与您所在地区相关的并搜索该requests行。
这是ARNrequests库相关的:
arn:aws:lambda:us-east-1:770693421928:layer:Klayers-python38-requests:6

所以现在在您的 lambda 函数中,使用找到的 ARN 添加一个层。
观察:确保您的 Python lambda 函数运行时是python3.8

  • 作为回购协议的所有者,我同意这个评论:) (6认同)
  • 好的,这就是使用恰好安装了“requests”包的 AWS Lambda 层。最好自己安装包,或者使用包含该包的 AWS 分布式层,而不是使用“未知”来源的层。 (2认同)

Yug*_*ari 5

如果您使用无服务器框架

指定插件在serverless.yml

plugins:
- serverless-python-requirements
Run Code Online (Sandbox Code Playgroud)

在根目录下创建文件requirements.txt

要求.txt

requests==2.22.0
Run Code Online (Sandbox Code Playgroud)

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