简体   繁体   中英

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. I'm trying to run the lambda_handler function in the aws_lambda_function module.

在此处输入图像描述

The code in aws_lambda_function is:

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:

在此处输入图像描述

I have found that when I comment out line 2 from aws_lambda_function, I get the following error instead: 在此处输入图像描述

This suggests to me that it's having a hard time with how I'm trying to import the server_code module. 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 (this produces the error 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. (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? 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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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