Md. Parvez Alam
Md. Parvez Alam

Reputation: 4596

serverless aws python lambda unable to import module from parent directory

I have following structure

enter image description here

I am trying to import utils inside handler.py

I tried giving like

from src.utils import *
from utils import *

also tried adding

import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

and

import os
    import sys
    
    sys.path.append('src')

but nothing working

I am using serverless framework not manually uploading the zip file

Tried alot but nothing working...

Any help, highly appreciated.

Thanks

Upvotes: 1

Views: 1427

Answers (2)

Dhinsha Mahesh
Dhinsha Mahesh

Reputation: 41

You can install serverless-functions-base-path plugin and use.

Check out the guide on the plugin here https://www.serverless.com/plugins/serverless-functions-base-path

If your serverless.yml file and src in the directory, you can add this to you serverless.yml file and try deploy

custom:
  functionsBasePath: src

plugins:
  - serverless-functions-base-path

Upvotes: 1

AnonymousAlias
AnonymousAlias

Reputation: 1399

You can use serverless-python-requirements plugin for this.

It can be installed locally or on a pipeline with

sls plugin install -n serverless-python-requirements 

You can add this to you serverless.yml file and try deploy

# this part might not be needed depending on size of utils
custom:
  pythonRequirements:
    zip: true

# This plugin allows us import dependencies
plugins:
  - serverless-python-requirements

Check out the guide on the plugin here

https://www.serverless.com/blog/serverless-python-packaging

https://www.npmjs.com/package/serverless-python-requirements

Upvotes: 0

Related Questions