erinc
erinc

Reputation: 267

(Python) Importing Code to Lambda Function from Lambda Layer Keeps Failing

I have a Lambda layer which includes my shared code (data models) and pip packages. I would like to import that to my Lambda function and use it. I am able to add the Lambda Layer, use the pip packages without any issues but when I try to import my models from this common layer. I keep getting the following error.

'errorMessage': "Unable to import module 'app': attempted relative import beyond top-level package"

I believe it is related to the folder structure of layer or function (more probable). I followed the convention for the Lambda Layer.

Below is the folder structure for my Layer.

├── LICENSE
├── README.md
├── __init__.py
├── python
│   ├── lib
│   │   └── python3.9
│   │       └── site-packages
│   ├── model
│   │   ├── __init__.py
│   │   ├── a.py
│   │   ├── b.py
├── requirements.txt
├── samconfig.toml
└── template.yaml

Here is the structure for my Lambda function:

├── README.md
├── __init__.py
├── events
│   └── event.json
├── openapi.yml
├── requirements.txt
├── samconfig.toml
├── src
│   ├── __init__.py
│   ├── app.py
│   ├── db.py
│   ├── service.py
├── template.yaml

What I try to do is import for example, a.py from model folder inside db.py, such as:

from model import a

but it results in the error I mentioned:

'errorMessage': "Unable to import module 'app': attempted relative import beyond top-level package", 'errorType': 'Runtime.ImportModuleError'

Upvotes: 0

Views: 484

Answers (1)

erinc
erinc

Reputation: 267

Resolved: Apparently it is not possible to import from a folder like this. I have deleted the model folder and created a new file under python directory, such as models.py, copy and pasted all my models inside that single file.

Now importing models in the form of: import A from models.py works.

One solution that could work is have my models in separate files but import all them into a models.py file and import from it from the function itself.

Upvotes: 1

Related Questions