1

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.

enter image description here

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:

enter image description here

I have found that when I comment out line 2 from aws_lambda_function, I get the following error instead: enter image description here

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.

2
  • This does work for me, maybe post full code on github and then attach link in your post or attach code somewhere and add a zip file link in your post so that people can try running your code. Commented Nov 26, 2022 at 8:19
  • I figured out what it was! Commented Nov 27, 2022 at 4:46

1 Answer 1

0

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!

Sign up to request clarification or add additional context in comments.

1 Comment

AWS isn't the issue there. That's how Python's package imports work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.