Deploying Flask on AWS Lambda

In this article, we will guide you to deploy a flask application onto AWS Lambda using Zappa. First, we will discuss what these actually are and then proceed with our main goal.

image

FLASK

Flask is a python's framework for building web applications. It follows WSGI toolkit and its lightweight when compared with other frameworks like python's Django and PHP's Drupal. It helps in setting up the application easily without any hassle. Generally, flask finds much of its use case in small projects but complex and database -driven are also developed using it.

AWS LAMBDA

Web applications activity is uncertain, sometimes they serve huge amounts of workloads but at times they may sit idle without any considerable request count. Hosting applications on an EC2 Instance or in containers like ECS make us pay for the idle time too. To address such a problem we need to look at load balancing, DNS lookups and auto-scaling. Managing all these is difficult.

AWS lambda is the perfect solution. It scales automatically when needed, depending upon the requests the application gets. Thus, making us pay only when we consume it. If our code is not running then charges are not incurred.

Settings AWS Credentials

Create a folder called aws at the root level,

mkdir .aws

Now, create a file called credentials and store the aws_access_key_id and aws_secret_access_key. The other specifics like default_region can alos be stored.

Firstly, to get the access credentials, do the following,

  • Goto IAM role in AWS dashboard.

  • Nagivate to Users.

  • Click on the Security credentials tab, and go down to Access Key, note down the access_key_id. secret_access_key is only visible when you are creating new user, so you need to note down both the access_key_id and secre_access_key at the time of user creation only.

To generate a new access_key, click on the create access key button,

aws_credentials

###~/.aws/credentials
[default]
aws_access_key_id=[...]
aws_secret_access_key=[...]

You can also use AWS cli to set the aws_access_key_id and aws_secret_access_key. To install aws_cli,

pip install awscli

Zappa helps in deploying and building any WSGI compatible applications that are developed in python. Flask, Django, Bottle and many other work with Zappa.

While using Zappa we dont actually need to change any of our code. It simply helps in visualizing the serverless hosting of your applications. Horizontal scaling is handled by Zappa and the applicatyion is never tightly coupled with it, so if we want to leave it, its very simple.

NOW, Lets get Started!

Until now, we got to know what all are required to deploy a flask application on to AWS Lambda. To get started we need to install all the required libraries and packages. Here we need, - Flask - Zappa

Let's create a project, flask-app.

mkdir flask-app

Creating Virtual Environment

Now change the working directory to flask-app and create a virtual environment first, this helps in setting up independent and separate python environments thus helping to work on different versions of the same package.

virtualenv .env
source .env/bin/activate

Create another file called requirements.txt and fill in the required packages. Here we need flask and Zappa, therefore add these two lines into the requirements file,

#requirements.txt
flask
zappa

Once you have listed out the requirements. Install them using PIP, its package manager used extensively to install python libraries and frameworks.

pip install -r requirements.txt

Once all the required packages are installed, we will start with a very basic flask app which simply says "HELLO WORLD!".

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify({"message": "Hello World!"})

if __name__ == '__main__':
 app.run()

The application is completed, now we need to focus on how to deploy this applcation onto Amazon lambda.

Now, the ZAPPA's part!

As mentioned previously, Zappa helps in easily deploying WSGI applications onto Amazon Lambda. Firstly, you need to create an AWS account. if there are multiple users are using the same AWS account then they should use unique names while using starting Zappa, because the names of the resources may get conflicted.

# zappa init
FULL OUTPUT TRUNCATED... 
What do you want to call this environment (default 'dev'):
What do you want call your bucket? (default 'zappa-ip7znwymz'):
Where is your app's function? (default 'app.init.app'):
Would you like to deploy this application globally? (default 'n') [y/n/(p)primary]:
Does this look okay? (default 'y') [y/n]:

After running zappa init command it will create a file called zappa_settings.json will helps in deploying your application.

Almost Done!

The important thing while deploying is to choose an environment name like dev, prod, alpha etc. This name should be unique. The flask application is deployed to AWS Lambda using the zappa_settings.json file.

zappa deploy dev

Example:

(.env)ubuntu@172-31-19-54:~/flask-app$ zappa deploy dev
Calling deploy for stage dev..
--TRUNCATED OUTPUT...
- 75%|█████████████████████████████████ | 3/4 [00:12<00:06, 6.95s/res]
- Deploying API Gateway..
- Deployment complete!: https://izg1p4sbdavs67.execute-api.us-west-2.amazonaws.com/dev

Acessing the application!

Check the deployment of your application by accessing it through API Gateway. That is, note down the url from the zappa deploy command and open it in any web browser.

https://izg1p4sbdavs67.execute-api.us-west-2.amazonaws.com/dev

If you update the application just run the update command in addition with the environment i.e

zappa update dev

The source code can be found on github

Hope the article was of help!

Comments