在 AWS lambda 中创建 utils.py

create utils.py in AWS lambda(在 AWS lambda 中创建 utils.py)

本文介绍了在 AWS lambda 中创建 utils.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 home/file.py 文件中有一个 def hello() 函数.我创建了一个 home/common/utils.py 文件并将函数移到那里.现在,我想将它导入我的文件 file.py.

I had a def hello() function in my home/file.py file. I created a home/common/utils.pyfile and moved the function there. Now, I want to import it in my file file.py.

我是这样导入的: from utils import hellofrom common.utils import hello 并且我的文件中的导入不会引发错误.但是,当我在 AWS Lambda 上运行它时,我收到一个错误:

I imported it like this: from utils import hello and from common.utils import hello and the import in my file doesn't throw an error. However, when I run it on AWS Lambda, I get an error that:

Runtime.ImportModuleError:无法导入模块文件":没有名为utils"的模块

我该如何解决这个问题?无需使用 Ec2 之类的...

How can I fix this? without having to use Ec2 or something...

data "archive_file" "file_zip" {
  type             = "zip"
  source_file      = "${path.module}/src/file.py"
  output_file_mode = "0666"
  output_path      = "${path.module}/bin/file.zip"
}

推荐答案

您上传的部署包仅包含您的主要 Python 脚本 (file.py).具体来说,它不包含任何依赖项,例如 common/utils.py.这就是代码在 Lambda 中运行时导入失败的原因.

The deployment package that you're uploading only contains your main Python script (file.py). Specifically, it does not include any dependencies such as common/utils.py. That's why the import fails when the code runs in Lambda.

修改您的创建部署包(file.zip),使其包含所有需要的依赖项.

Modify the creation of your deployment package (file.zip) so that it includes all needed dependencies.

例如:

data "archive_file" "file_zip" {
  type             = "zip"
  output_file_mode = "0666"
  output_path      = "${path.module}/bin/file.zip"

  source {
    content  = file("${path.module}/src/file.py")
    filename = "file.py"
  }

  source {
    content  = file("${path.module}/src/common/utils.py")
    filename = "common/utils.py"
  }
}

如果您的所有文件碰巧都在一个文件夹中,那么您可以使用 source_dir 而不是指示单个文件.

If all of your files happen to be in a single folder then you can use source_dir instead of indicating the individual files.

注意:我不使用 Terraform,所以带有嵌入插值的 file(...) 可能不是 100% 正确,但你明白了.

Note: I don't use Terraform so the file(...) with embedded interpolation may not be 100% correct, but you get the idea.

这篇关于在 AWS lambda 中创建 utils.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 AWS lambda 中创建 utils.py

基础教程推荐