- Newest
- Most votes
- Most comments
The issue you're experiencing with your AWS Lambda function failing to import the module 'templates.portada.cover_page' despite the file existing in your container is likely related to how Python searches for modules within the Lambda execution environment.
When using container images with Lambda, it's important to understand that the Python runtime has a specific search path for modules. By default, it first searches the {LAMBDA_TASK_ROOT} directory, which is typically /var/task in the Lambda environment.
Even though you've set PYTHONPATH=/var/task, there might be a discrepancy between how modules are found when you test locally versus how they're located in the actual Lambda environment. The Lambda runtime might be using a different search path or not respecting the PYTHONPATH as expected.
To troubleshoot this issue, you can try the following:
-
Ensure that your app.py file (containing the lambda_handler function) is at the root of your /var/task directory.
-
Modify your code to print out the sys.path at the beginning of your lambda_handler function. This will show you the exact search path being used by the Lambda runtime.
-
Consider restructuring your project so that the 'templates' directory is at the same level as your app.py file, making it easier for Python to locate.
-
If you're using Python 3.9, be aware that runtime-included libraries are installed in the /var/runtime directory, which takes precedence over /var/lang/lib/python3.x/site-packages in the search path. This could potentially interfere with your custom modules.
-
Double-check that all init.py files are present and properly structured to make your package importable.
-
As a last resort, you might need to modify your import statement to use an absolute import path, although this is generally not recommended as it can make your code less portable.
If these steps don't resolve the issue, you may need to review how your container image is built and ensure that all files are placed in the correct locations within the image. Additionally, consider using the Lambda runtime interface emulator to test your function locally in an environment that more closely mimics the actual Lambda runtime.
Sources
Deploy Python Lambda functions with container images - AWS Lambda
Unable to Import Lambda Function Module: No module named 'lambda_function' | AWS re:Post
Relevant content
- asked 8 months ago