简体   繁体   中英

AWS Lambda Python - How to import modules from local files to app.py

This is a simple SAM-template based deploy with a Docker container. Filesystem structure:

src/app.py
    mymodule.py

In app.py:

from .mymodule import myfunction

Result (on invoke):

Unable to import module 'app': attempted relative import with no known parent package

Removing the dot results in:

Unable to import module 'app': No module named 'mymodule'

Adding the local directory to path does not help either:

import os, sys
currentdir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(currentdir)

Now I guess this appears to be due to the limitations described in the great answer from Relative imports for the billionth time

ie app.py is being run as a script, not a module, and scripts cannot import relatively

The workarounds in the above answer both require changing some way the Lambda function is built and/or invoked - how to do this is the question?

Add __init__.py file to your src folder (same level as ur app.py)

Or if you are using container, make sure your Dockerfile copies everything and not just app.py

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