DEV Community

Apcelent
Apcelent

Posted on

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.

Alt text of 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.

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!

The article originally appeared on Apcelent Tech Blog.

Top comments (6)

Collapse
 
thejessleigh profile image
jess unrein • Edited

I'm just starting to get into and understand serverless architecture. What's the use case for deploying an entire web application on AWS Lambda, rather than extracting the functionality into single purpose tasks, Dockerizing them, and deploying those as Lambdas? It's my understanding that the resources available on Lambda are pretty limited, so anything that requires a full web framework or database connection probably isn't a good use case for Lambda.

But like I said, I just started learning about serverless, so I'm still trying to wrap my brain around good vs. bad implementations. :)

Collapse
 
thebouv profile image
Anthony Bouvier

What I've used Lambda + Flask + Zappa for is Amazon Alexa Skills. I used to have them written in NodeJS, but have been rewriting them all with Flask-Ask ( github.com/johnwheeler/flask-ask ) and deployed to Lambda.

Collapse
 
kdt74 profile image
KDT74

(This question was left hanging. I hope it is still useful for someone.)

I haven’t deployed Python/Flask implementation with lambda, but I have done something similar with JavaScript Node/Express and C#/WebAPI. Basically they all use API Gateway with proxy integration where the entire request is sent to your lambda and it’s responsible for all of the request routing, response, security, etc.

The advantages are:

  • fewer cold starts. The traditional method of using one lambda per request, means that endpoint is mostly likely to see a delay if it hasn’t been hit recently.

  • familiar development work flow: locally you work with the same tools that you are use to.

  • portability. I created a REST API that allows us to save and retrieve documents to/from S3. I knew I was going to hit the 6MB lambda request limit and eventually I was going to have to move it from lambda. I was able to move it to Fargate (more below) without any code changes. We had no experience with a Fargate at the time and we had to get it done.

I wouldn’t do an “entire website” with it though. The usual pattern is to host your REST API in lambda, host your website in S3, and use a client side framework.

Now on to Docker. You’re mixing to concepts. Docker/Fargate is its own serviceless offering. It’s more expensive than lambda, but it has advantages of being able to run continuously with no coldstarts. No request/response limit. and more options for CPU/Memory.

Collapse
 
thomasbourimechwni profile image
thomasbourimechwni • Edited

Same question here. We have developped our own Framework (Services, DAO etc...) that is served by flask. Have you found a way to incorporate it into AWS Lambda?

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
raphael_jambalos profile image
Raphael Jambalos

Great article! Thanks!!