Serverless cannot import local files;in same directory; into python file

2k Views Asked by At

I have a serverless code in python. I am using serverless-python-requirements:^4.3.0 to deploy this into AWS lambda. My code imports another python file in same directory as itself, which is throwing an error.

serverless.yml:

functions:
  hello:
    handler: functions/pleasework.handle_event
    memorySize: 128
    tags:
      Name: HelloWorld
      Environment: Ops
    package:
      include:
        - functions/pleasework
        - functions/__init__.py
        - functions/config

(venv) ➜  functions git:(master) ✗ ls
__init__.py             boto_client_provider.py config.py               handler.py              sns_publish.py
__pycache__             cloudtrail_handler.py   glue_handler.py         pleasework.py

As you can see, pleasework.py and config are in same folder, but when I do import config in pleasework I get an error:

{
  "errorMessage": "Unable to import module 'functions/pleasework': No module named 'config'",
  "errorType": "Runtime.ImportModuleError"
}

I am struggling with this for few days and think I am missing something basic.

import boto3
import config


def handle_event(event, context):
    print('lol: ')
2

There are 2 best solutions below

0
On

@Pranay Sharma's answer worked for me.

An alternate way is creating and setting PYTHONPATH environment variable to the directory where your handler function and config exist.

To set environment variables in the Lambda console

  1. Open the Functions page of the Lambda console.
  2. Choose a function.
  3. Under Environment variables, choose Edit.
  4. Choose Add environment variable.
  5. Enter a key and value.

In our case Key is "PYTHONPATH" and value is "functions"

0
On

ok, so i found out my isssue. Way i was importing the file was wrong Instead of

import config

I should be doing

import functions.config