2
votes

I am working on a project that is using AWS CodeBuild to deploy a Serverless (SLS) function that is written in Python.

The deployment works fine within code build. It successfully creates the function and I can view the lambda within the Lambda AWS UI. Whenever the function is triggered, I get the error seen below:

Runtime.ImportModuleError: Unable to import module 'some/function': attempted relative import with no known parent package

It is extremely frustrating as I know the function exists at that directory listed above. During the CodeBuild script, I can ls into the directory and confirm that it indeed exists. The function is defined in my serverless.yml file as follows:

functions:
  file-blaster:
    runtime: python3.7
    handler: some/function.function_name
    events:
      - existingS3:
          bucket: some_bucket
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: ${opt:stage}/some/prefix

Sadly, I haven't been able to crack this one. Has anyone had a similar experience while working with SLS and python in the cloud?

It seems odd that SLS would build and deploy successfully, but the Lambda itself cant find the function.

2

2 Answers

3
votes

This will be a short answer for what is a somewhat longer discussion on Python imports. You can do the research yourself on the hectic and confusing battle between relative and absolute imports as a design for a python project.

The Gist: It is necessary to understand that the base of the python importing for SLS functions IS where the serverless.yml file exists (I imagine that it is similar to having a main.py that calls the other files that are referenced as "functions" in the sls yml). For my case above, I did not structure the imports using absolute imports when I had my issues. I switched all of my imports to have absolute paths, so when I moved the package around, it would continue to work.

The error that I was given Runtime.ImportModuleError: Unable to import module 'some/function': attempted relative import with no known parent package was really poor to describe the actual issue. The error should have included that the packages being used by some/function were not found when attempting a relative import because that was the actual problem that needed fixing.

Hopefully this helps someone else out someday. Let me know if I can provide more information where I haven't already.

1
votes

I think you need to change your handler property from :

handler: some/function.function_name

to

handler: some/function.{lambda handler name}

like, my folder structure is:

- some
  - function1.py

then my template will be:

functions:
  file-blaster:
    runtime: python3.7
    handler: some/function1.lambda_handler

for more details check here https://serverless.com/framework/docs/providers/aws/guide/functions/