简体   繁体   English

如何告诉 AWS Lambda 如何访问相关文件 Python

[英]How to tell AWS Lambda how to access relative files Python

I'm trying to get some Python code to run on AWS Lambda. This is my file structure.我正在尝试让一些 Python 代码在 AWS Lambda 上运行。这是我的文件结构。 I'm trying to run the lambda_handler function in the aws_lambda_function module.我正在尝试在aws_lambda_function模块中运行lambda_handler function。

在此处输入图像描述

The code in aws_lambda_function is: aws_lambda_function中的代码是:

import json
from server.server_code import process_request

def lambda_handler(event, context):
    response = process_request(event)
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

I am telling the lambda to look for the code to run here:我告诉 lambda 寻找要在此处运行的代码:

在此处输入图像描述

I have found that when I comment out line 2 from aws_lambda_function, I get the following error instead:我发现当我从 aws_lambda_function 注释掉第 2 行时,我得到以下错误: 在此处输入图像描述

This suggests to me that it's having a hard time with how I'm trying to import the server_code module.这向我表明,我在尝试导入 server_code 模块时遇到了困难。 I've tried each of the following:我尝试了以下各项:

from.server_code import process_request (this produces the same error about relative imports beyond top-level packages) from.server_code import process_request (这会产生与顶级包之外的相对导入相同的错误)

from server_code import process_request (this produces the error Unable to import module 'server.aws_lambda_function': No module named 'server_code' ) from server_code import process_request (这会产生错误Unable to import module 'server.aws_lambda_function': No module named 'server_code'

I've read a lot of articles and Stack exchange threads about how to tackle this issue of relative imports in Python, but following their instructions haven't made a difference so far.我在 Python 中阅读了很多关于如何解决这个相对导入问题的文章和 Stack 交换线程,但按照他们的说明到目前为止并没有什么不同。 (Note: I have been clicking the "Deploy" button each time I make a change.) (注意:我每次进行更改时都单击“部署”按钮。)

Any thoughts on how I can make it so that my handler can reference this function from the server_code.py file?关于如何使我的处理程序可以从 server_code.py 文件中引用此 function 的任何想法? It works fine when I run the code locally on my machine.当我在我的机器上本地运行代码时,它工作正常。

Okay, so it turns out that these AWS messages aren't the most descriptive or helpful for finding where the actual bugs are.好吧,事实证明,这些 AWS 消息并不是最具描述性或有助于查找实际错误所在的位置。 It turns out that what I had to do was to go through recursively through every folder in this directory, add an __init__.py file to make the folder a package, and then remove all relative imports and replace them with really long, absolute imports starting with the parent package. That did the trick!事实证明,我必须做的是通过递归遍历此目录中的每个文件夹到 go,添加一个__init__.py文件使文件夹成为 package,然后删除所有相对导入并用非常长的绝对导入替换它们开始与父母 package 一起。成功了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM