Book Image

Building Serverless Python Web Services with Zappa

By : Abdulwahid Abdulhaque Barguzar
Book Image

Building Serverless Python Web Services with Zappa

By: Abdulwahid Abdulhaque Barguzar

Overview of this book

Serverless applications are becoming very popular these days, not just because they save developers the trouble of managing the servers, but also because they provide several other benefits such as cutting heavy costs and improving the overall performance of the application. This book will help you build serverless applications in a quick and efficient way. We begin with an introduction to AWS and the API gateway, the environment for serverless development, and Zappa. We then look at building, testing, and deploying apps in AWS with three different frameworks--Flask, Django, and Pyramid. Setting up a custom domain along with SSL certificates and configuring them with Zappa is also covered. A few advanced Zappa settings are also covered along with securing Zappa with AWS VPC. By the end of the book you will have mastered using three frameworks to build robust and cost-efficient serverless apps in Python.
Table of Contents (20 chapters)
Title Page
Dedication
Packt Upsell
Contributors
Preface
Index

How AWS Lambda works


You need to write a function, which will be executed by AWS Lambda on your behalf.

AWS Lambda is implemented on a container-based model that supports a runtime environment and executes the code as per the Lambda function configuration. When the Lambda function is invoked, it launches the container (an execution environment) based on the AWS Lambda configuration and enables the basic runtime environment, which is required to execute the code.

Let's start with some practical work:

  1. To create a Lambda function, you must have an AWS account. If you don't have an AWS account, then you need to sign up on AWS (https://aws.amazon.com/) by providing some basic contact and payment information, as it's essential information required by Amazon.
  2. Go to the Lambda home page (https://console.aws.amazon.com/lambda/home). Click on the Create a function button. This will redirect you to the Create function page, which is described in the next step. Take a look at the following screenshot:

  1. AWS provides three different options to create a Lambda function, such as Author from scratch, Blueprints, and Serverless Application Repository. We will be using the Blueprint option, which has some built-in Lambda functions. We can choose these blueprints based on our requirements from the search bar, where you can filter by tag and attributes or search by keywords:

  1. Let's choose a hello-world-python blueprint. Once we choose the blueprint, we need to set up the basic information about the Lambda function. This information includes the Lambda function's Name and Role, as shown in the following screenshot:

  1. Here, Name will be a unique identification for your Lambda function and Role defines the permissions of your Lambda function.

There are three options available for creating a role:

  • Choose an existing role
  • Create new role from template(s)
  • Create a custom role Let's look at them in more detail:
    • Choose an existing role: This allows you to select the previously created role.
    • Create new role from template(s): Here, you need to define a role name. AWS Lambda provides ready-made built-in role policy templates that have pre-configured permissions. These are based on other AWS services-related permissions required by the AWS Lambda function. On any role selection, Lambda will automatically add the logging permission to CloudWatch (AWS logging service), as this is the basic permission required by Lambda.
    • Create a custom role: AWS provides an additional privilege to create a customized role to access AWS Lambda. Here, you can define the role based on your requirement.
  1. Let's create the HelloWorld Lambda function with some role. Here, I chose the S3 object read-only permission policy template.
  1. The following screenshot describes the newly created HelloWorld Lambda function:

HelloWorld Lambda function

The Lambda function includes three sections:

  • Configuration
  • Triggers
  • Monitoring

Let's look at detailed information about the configuration and monitoring. We will have a separate section for triggers. 

Configuration

Lambda execution depends on the configuration setting. Configuring the Lambda function requires the following details:

  • Function code
  • Environment variables
  • Tags
  • Execution role
  • Basic settings
  • Network
  • Debugging and error handling

Function code

Here, you are required to write the code. The Lambda function has a predefined pattern for writing the code. While writing the code, you need to understand the context. Lambda provides three kinds of feasibility, which decides your runtime execution for the code:

  • Code entry type: This section provides three options to decide the entry type for your code, such as editing code inline, uploading a ZIP file, and uploading a file from Amazon S3.
  • Runtime: This section provides options to decide the runtime programming language context for your code, such as Python, C#, NodeJS, and Java.
  • Handler: A handler defines the path to your method/function, such as <filename>.<method_name>. For example, if you want to execute a function named as a handler, which is defined in main.py, then it would be main.handler.

Let's get back to our newly created hello world function named lambda_handler.

Here, the handler value is defined as lambda_function.lambda_handler, where lambda_function.py is the filename and lambda_handler is the method name:

def lambda_handler(event, context): 
    print("value1 = " + event['key1']) 
    print("value2 = " + event['key2']) 

Lambda_handler accepts two positional arguments, event and context:

  • event: This argument contains event-related information. For example, if we configure the Lambda function with Amazon S3 bucket events, then we would get S3 bucket information in event arguments, such as bucket name, region, and so on.
  • context: This argument contains the context-related information that may be required during runtime for code execution.

Environment variables

You can set the environment variables in key-value pairs, which can be utilized in your code.

Tags

You can use tags for grouping and filtering your Lambda functions. You may have multiple Lambda functions with different regions, so tags help make Lambda functions more manageable.

Execution role

As we previously discussed the role and permission while creating the Lambda function, Lambda provides the capability to edit the existing role that you chose at the time of the Lambda function creation.

Basic settings

Under basic settings, you can configure the memory and execution timeout. Lambda supports memory from 128 MB to 1,536 MB. Timeout execution is in seconds; the default timeout execution Lambda supports is 300 seconds. This setting helps you to control the code execution performance and cost for your Lambda function.

Network

In the network section, you can configure the network access to your Lambda function.

AWS provides a VPC (Virtual Private Cloud) service to create a virtual network, which allows access to AWS services. You can also configure the networking as per your requirements.

We will discuss the Lambda function with VPC in the upcoming chapters. As of now, we will choose No VPC in the network section.

Debugging and error handling

AWS Lambda automatically retries the failed asynchronous invocation. But you can also configure the DLQ (Dead Letter Queue), such as the SQS queue or SNS topic. To configure the DLQ, the Lambda function must have permission to access DLQ resources.

Now that we understand the configuration, let's go ahead with the execution of the Lambda function.

Let's look at the Monitoring section, which describes the activity related to our Lambda function. It can be used to analyze the performance of our Lambda function execution.

Monitoring

AWS CloudWatch is a monitoring service for AWS resources and manages all activity logs. It creates metric data to generate statistical data. CloudWatch enables real-time monitoring of AWS resources. It also monitors hardware information related to AWS EC2 or RDS database instances and other resources.

Lambda monitoring sections display the last 24 hours' analytics data related to the Lambda function's activity and performance. The following screenshot shows the monitored analytics information about our hello world Lambda function:

Let's move on to the next section, where we are going to look at the Lambda function execution.