在 python 中使用 AWS Lambda 将 Post 请求发送到外部 API

新手上路,请多包涵

我想每小时向外部 API ( https://example.com/api/jobs/test ) 发送一个发布请求。

我使用的 Lambda 函数如下:

 Handler: index.lambda_handler
python: 3.6

索引.py

 import requests
def lambda_handler(event, context):
  url="https://example.com/api/jobs/test"
  response = requests.post(url)
  print(response.text) #TEXT/HTML
  print(response.status_code, response.reason) #HTTP

测试事件:

  {
 "url": "https://example.com/api/jobs/test"
}

错误:

  START RequestId: 370eecb5-bfda-11e7-a2ed-373c1a03c17d Version: $LATEST
 Unable to import module 'index': No module named 'requests'

 END RequestId: 370eecb5-bfda-11e7-a2ed-373c1a03c17d
 REPORT RequestId: 370eecb5-bfda-11e7-a2ed-373c1a03c17d Duration: 0.65 ms   Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 21 MB

任何帮助,将不胜感激。

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

阅读 788
2 个回答

您需要将 requests 模块安装到您的项目目录并创建一个 lambda 部署包。有关详细信息,请参阅 链接。

简而言之,您需要在开发系统(PC 或 mac)上创建 index.py 文件,在该系统上安装 Python 和 pip;他们按照文档中的步骤操作。要创建 lambda,请选择“上传 zip”选项而不是“编辑内联”选项

原文由 agent420 发布,翻译遵循 CC BY-SA 3.0 许可协议

供应商 requests 现在已从 botocore 中删除。

考虑使用 CloudFormation 包或 SAM CLI 打包功能将您的 Lambda 代码打包为 requirements.txt

我之前的旧答案出售 requests 弃用:您可以利用 requests 来自 boto 的模块,而无需安装或打包您的函数库。

考虑这个导入: import botocore.vendored.requests as requests

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

推荐问题