Prepare the Source Code

Prepare the Source Code

  1. Source Code.

    • To practice in this Lab, I’ve prepared a source code written in Django - Python. You can clone it to experiment with serverles-django-demo.
  2. Explanation of the Mangum library.

    • Mangum is a Python library designed to support deploying ASGI (Asynchronous Server Gateway Interface) applications on AWS Lambda. This library acts as a converter, allowing ASGI applications to handle events from various AWS services, including API Gateway, Application Load Balancer (ALB), and Lambda@Edge. This is very useful for developers who want to leverage serverless architecture while using modern Python frameworks like FastAPI, Starlette, and Django.

    The process works as follows:

    • Receiving an Event from API Gateway: When an HTTP request is sent to API Gateway, it generates an event containing information about the request, including the HTTP method, path, headers, body, etc. This event is then sent to the Lambda function.
    • Converting the Event to ASGI: Mangum receives this event and converts it into an ASGI-compliant request, including Headers, Body, Path, and Method.
    • Converting the Response: After Django processes the request, a response will be generated in the ASGI format. Mangum receives this response and converts it back into the format required by API Gateway, including Headers, Body, Status Code.
    • Sending the Response back to API Gateway: Finally, the converted response is sent back to API Gateway, which then returns it to the client (the user or system that made the initial request).
  3. Preparing the Dockerfile

FROM public.ecr.aws/lambda/python:3.9
ADD . "${LAMBDA_TASK_ROOT}"
RUN pip3 install -r "${LAMBDA_TASK_ROOT}"/req.txt --target "${LAMBDA_TASK_ROOT}"
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD ["lambda_handler._handler"]
  • public.ecr.aws/lambda/python:3.9: This is the base image provided by AWS, containing the Python 3.9 runtime environment and the necessary tools to run a Lambda function on the AWS Lambda platform.
  • In the context of AWS Lambda and API Gateway, the handler is the entry point for all events sent to the Lambda function. When an event (such as an HTTP request from API Gateway) occurs, AWS Lambda invokes the specified handler. Therefore, we need to specify the correct handler in this Docker Image.