python - 无法在 AWS Lambda 上使用请求模块

标签 python python-2.7 amazon-web-services aws-lambda

我需要在每天运行一次的 python 脚本中进行休息调用。 我无法使用 AWS Lambda 将“请求”包打包到我的 python 包中。我收到错误消息:“无法导入模块 'lambda_function':没有名为 lambda_function 的模块”

我将其分解为 hello_world 预定义脚本。我可以把它打包成一个 zip 并上传。一切正常。一旦我将“导入请求”放入文件中,我就会收到此错误。

这是我已经做过的:

  1. zip 和项目文件夹(包括子文件夹)的权限设置为 `chmod 777`。所以权限应该不是问题。
  2. 脚本本身位于根文件夹中。当你打开 zip 文件时,你会直接看到它。
  3. 我使用 `sudo pip install requests -t PATH_TO_ROOT_FOLDER` 将 requests 包安装到项目的根文件夹中

一切的命名是这样的:

  • 压缩文件:lambda_function.zip
  • py 文件:lambda_function.py
  • 处理方法:lambda_handler(event, context)
  • “webconfig: lambda_function.lambda_handler”中的处理程序定义

最后我要运行的文件是这样的:

import requests
import json


def lambda_handler(event, context):
    url = 'xxx.elasticbeanstalk.com/users/login'
    headers = {"content-type": "application/json", "Authorization": "Basic Zxxxxxxxxx3NjxxZxxxxzcw==" }
    response = requests.put(url, headers=headers, verify=False)
    return 'hello lambda_handler'

我很高兴能得到任何帮助。我已经在这个问题上使用了多个小时。

最佳答案

编辑:2019 年 10 月 21 日,Botocore 删除了请求的供应版本:https://github.com/boto/botocore/pull/1829

编辑 2:(2020 年 3 月 10 日):Lambda 服务在 AWS 开发工具包中捆绑请求模块的弃用日期现在是 2021 年 1 月 30 日。https://aws.amazon.com/blogs/compute/upcoming-changes-to-the-python-sdk-in-aws-lambda/

要使用 requests 模块,您可以简单地从 botocore.vendored 导入 requests。例如:

from botocore.vendored import requests

def lambda_handler(event, context):
   response = requests.get("https://httpbin.org/get", timeout=10)
   print(response.json())

你可以看到this gist了解更多可以直接在 AWS lambda 中导入的模块。

关于python - 无法在 AWS Lambda 上使用请求模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40741282/

相关文章:

python - Django SimpleLazyObject

python - Tensorflow 的教程 GAN 不适用于 CIFAR-10

python - 追踪 Python 2 中的隐式 unicode 转换

typescript - 如何在现有堆栈 AWS Cloudformation 中创建新实例

c# - 上传带有 MD5 哈希结果的流在 "The Content-MD5 you specified was invalid"

amazon-web-services - AWS IAM 访问 key 和 AWS 实例 key 文件 (.pem) 之间有什么区别?

python - Python中人脸识别的Face Anti-Spoofing方法

python - 如何通过路径导入python文件?

python - python mplot3D 中的 2D 图与 3D 轴壁不齐平

python-2.7 - 为Python机器学习(朴素贝叶斯)算法创建特征字典