I have the following structure of my AWS lambda project:
module
app.py
b.py
app.py
is my default aws lambda function with lambda_handler
, it works fine. I decided to pull all the heavy calculations out of it to function calc
of b.py
.
Then, I imported it to app.py
:
from module.b import calc
Now, when I run it locally with sam local invoke Function --event events/event.json
, it raises an error:
{"errorType":"Runtime.ImportModuleError","errorMessage":"Unable to import module 'app': No module named 'module'"}
It seems to me that when it prepares the code to run, it moves the files to some other directory, so the imports break. To fix this, I tried to use relative import:
from .b import calc
But it also raised an error:
{"errorType":"Runtime.ImportModuleError","errorMessage":"Unable to import module 'app': attempted relative import with no known parent package"}
How do I setup a multi-file python application on aws lambda?
This is how me resolve that problem.
First your root folder need to seem like this:
Now... When I use multiple files... I always use a lib folder. Like this:
IMPORTANT
Inside your lib folder you always need an
__init__.py
or you can't see the files inside.NOTE: the
__init__.py
needs to have the two underscores before and afterinit
.EXAMPLE
lib1.py
lambda_function.py
And that's all.