I have the simplest possible Python function and I am able to deploy it as an AWS Lambda function.
The code of the function is this
handler.py
import json
def ask(event, context):
body = {
"message": f"Go Serverless v3.0! Your function executed successfully! Length ",
"input": event,
}
response = {"statusCode": 200, "body": json.dumps(body)}
return response
The serverless.yml is this
service: rag-se-aws-lambda
frameworkVersion: ‘3’
provider:
name: aws
runtime: python3.11
package:
individually: true
functions:
ask:
handler: handler.ask
events:
- httpApi:
path: /
method: post
Now I develop a function my_function
in the file src/my_function.py and I want to use it in handler.py like this
import json
from src.my_function import my_function
def ask(event, context):
my_function()
body = {
"message": f"Go Serverless v3.0! Your function executed successfully! Length ",
"input": event,
}
response = {"statusCode": 200, "body": json.dumps(body)}
return response
When I deploy, with the same serverless.yml configuration, the new version of my function I get the following runtime error
Unable to import module ‘handler’: No module named ‘my_function’
By the way, if the file my_function.py is moved to the same root folder where handler.py is defined, everything works.
What should I do to be able to import a function from a different folder when using AWS Lambda python functions?
0
Since folder location makes difference, simply add your src
folder to Python’s sys.path
to let it find your stuff:
import json
import sys
import os
src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'src')
sys.path.append(src_dir)
from my_function import my_function
def ask(event, context):
my_function()
body = {
"message": "Go Serverless v3.0! Your function executed successfully!",
"input": event,
}
response = {"statusCode": 200, "body": json.dumps(body)}
return response