Python AWS Lambda Module Not Found

Viewed 913

I have an AWS Lambda implemented in Python 3.7 and deployed in a package arranged as below:

universe-UIFunctionCelestial-XXXX
|--universe-0-0-1-SNAPSHOT
| |--src
| | |--lambdas
| | | |--__init__.py
| | | |--celestial_persist_function.py
| | |--__init__.py

The following image shows this package as deployed in the AWS console: code portion of Lambda console

The Lambda is accessible via API Gateway. Its GET method successfully invokes the Lambda, however the Lambda returns the following error:

Wed Mar 04 09:49:35 UTC 2020 : Endpoint response body before transformations: {"errorMessage": "Unable to import module 'universe-0-0-1-SNAPSHOT/src/lambdas/celestial_persist_function': No module named 'src'", "errorType": "Runtime.ImportModuleError"}

Wed Mar 04 09:49:35 UTC 2020 : Lambda execution failed with status 200 due to customer function error: Unable to import module 'universe-0-0-1-SNAPSHOT/src/lambdas/celestial_persist_function': No module named 'src'. Lambda request id: 381990d0-f193-4e49-b0fa-2c6d736552bd

Wed Mar 04 09:49:35 UTC 2020 : Method completed with status: 502

I was under the impression that the Python Lambda execution imports the lambda as a module, so I added __init__.py files at each level. Thes might help the lambda import as well as the imports within the lambda like:

from src.persistence.persistence_service import PersistenceService

Anyway, I have tried a number of different arrangements and file structures. What might I might be doing wrong?

Incidentally, all the code executes locally without any issues.

2 Answers

I'm not experienced in Python, but looks like you should upload your code with another root folder. Please, try to move ..../src/ to /

P.S. And I recommend to use serverless.com framework to build your lambdas - it's much more easier for start

It's have been a while since the question was asked but I will answer it anyway - maybe it will help someone else.

I had the same issue - the thing with Lambda is that it runs inside the src folder and it does not understand your imports. What you need to have instead is:

    from [folder inside src] import [filename]

therefore your imports should look like this:

    from persistence import persistence_service

After this you will be able to invoke PersistenceService.

Related