Home Backend Development Python Tutorial Relative Python imports in a Dockerized lambda function

Relative Python imports in a Dockerized lambda function

Dec 23, 2024 pm 10:47 PM

Relative Python imports in a Dockerized lambda function

Relative Python imports can be tricky for lambda functions. I wrote a blog on this 3 years ago. But recently, I ran into the same issue with Dockerized lambda functions. So, I figured it was time for a new blog!

You can follow along with the steps or look at the result directly on GitHub.

Project setup

Make sure you installed the AWS CDK cli.

brew install aws-cdk
Copy after login

Initialize the project:

cdk init app --language=typescript
Copy after login

Lambda setup

First we will need to create the file and folder structure:

mkdir -p lib/functions/hello-world/hello_world
touch lib/functions/hello-world/hello_world/__init__.py
touch lib/functions/hello-world/requirements.txt
touch lib/functions/hello-world/Dockerfile
Copy after login

Now you will need to fill the Dockerfile, like this:

FROM public.ecr.aws/lambda/python:3.12
COPY requirements.txt .
COPY hello_world ${LAMBDA_TASK_ROOT}/hello_world
RUN pip install --no-cache-dir -r requirements.txt
CMD ["hello_world.handler"]
Copy after login

We are using a Python base image that is based on Python 3.12. Next, we will copy in the requirements.txt file and the source code. We will install all dependencies listed in the requirements.txt file and make sure that the handler method is set as the CMD.

Next, we will need to fill our Python files with some code. In the __init__.py file, you can place the following content:

from typing import Dict, Any


def handler(event: Dict[str, Any], context: Any) -> Dict[str, str]:
    name = event.get("name", "World")

    return {
        "Name": name,
        "Message": f"Hello {name}!",
    }


__all__ = [
    "handler"
]
Copy after login

NOTE: The code used here could use relative imports. This is possible because it is in a separate package. This example only shows the code in the __init__.py file. However, you can use multiple files here to improve the maintainability of your project.

For this example, I don't need any dependencies, so we can keep the requirements.txt file empty. I included it in this example to illustrate how you can include dependencies as well.

Create the Lambda function using IaC

Our folders and files are in place, so it is time to add the Lambda function to the CDK construct. You can simply add it like this:

    new lambda.Function(this, 'Function', {
      functionName: "hello-world",
      code: lambda.Code.fromAssetImage("lib/functions/hello-world", {
        platform: ecr_assets.Platform.LINUX_ARM64,
      }),
      runtime: lambda.Runtime.FROM_IMAGE,
      handler: lambda.Handler.FROM_IMAGE,
      architecture: lambda.Architecture.ARM_64,
      timeout: cdk.Duration.seconds(15),
      memorySize: 128,
    });
Copy after login

For this to work, you also need the following imports:

import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets';
Copy after login

Note that we make sure that the code directory points to the directory that contains the Dockerfile and that we select the ARM platform for both the code and the function itself.

Testing the lambda function locally

Fast feedback is important, so there might be cases where you need to run the container locally. For this, you first need to build the container:

docker build --platform linux/arm64 \
  -t hello-world:latest \
  -f ./lib/functions/hello-world/Dockerfile \
  ./lib/functions/hello-world
Copy after login

Note that this command can be executed from the project's root. Next, we need to make sure it's running before we can invoke it:

docker run --platform linux/arm64 -p 9000:8080 hello-world:latest
Copy after login

Afterwards, you can invoke the function as follows:

curl http://localhost:9000/2015-03-31/functions/function/invocations -d '{"name": "Joris"}'
Copy after login

Conclusion

Relative imports can be tricky! You need to place your code in a package. This allows you to do relative imports within your own package. This will enable cleaner code, as you can split responsibilities into multiple files, making it easier to manage and maintain.

Photo by Kaique Rocha

The above is the detailed content of Relative Python imports in a Dockerized lambda function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

Explain the purpose of virtual environments in Python. Explain the purpose of virtual environments in Python. Mar 19, 2025 pm 02:27 PM

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.

See all articles