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

Django

Django is a python's framework for developing web applications. It follows WSGI toolkit and comes with many features like dynamic admin interface, ORM ability, powerful cache framework, built-in template system, easy database migrations, security features etc.

You can view the full documentation at [Django-documentation]. The tutorial is very helpful and covers most of the core topics.

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 [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. It uses three products namely AWS Lambda and AWS API Gateway, and Amazon s3.

It uses Amazon S3 to upload your application code and then AWS Lambda uses this zipped up code to run the application. It deploys the application with a single command zappa deploy but we need to configure many options through zappa cli.

Let's build a django app first!

Before building Django app you need to install all the required packages. Create a file called requirements.txt and fill in all the requirements.

django zappa

Create a virtual environment so that we can use different versions of the same packages and frameworks. To create a virtual environment, you need to install virtualenv.

pip install virtualenv

After installing virtualenv, set up one and install the requirements in a separate folder,

mkdir django-app cd django-app

Create the environment,

virtualenv .env

Activate it by typing,

source .env/bin/activate

Installing the required packages, here we have listed all the requirements in requirements.txt file, so type the following command,

pip install requirements.txt

Now, we will start a very basic Django app, and check if everything is working.

django-admin startproject sampledjango .

Run the server to check the status of the application,

python manage.py runserver

Using Zappa!

Our application doesn't provide much at this moment, it just a sample application. But even if the application is bundled with hundreds of APIs and thousands of modules the deployment procedure using zappa is same.

Zappa should be initialized first, but before doing that I'm assuming that you have a valid aws account.

Intializing Zappa,

zappa init

It will output something like this,

███████╗ █████╗ ██████╗ ██████╗ █████╗ ╚══███╔╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗ ███╔╝ ███████║██████╔╝██████╔╝███████║ ███╔╝ ██╔══██║██╔═══╝ ██╔═══╝ ██╔══██║ ███████╗██║ ██║██║ ██║ ██║ ██║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ Welcome to Zappa! Zappa is a system for running server-less Python web applications on AWS Lambda and AWS API Gateway. This `init` command will help you create and configure your new Zappa deployment. Let's get started! Your Zappa configuration can support multiple production stages, like 'dev', 'staging', and 'production'. What do you want to call this environment (default 'dev'):

Zappa takes aws details using aws credentials file (contains aws_access_key_id and aws_access_secret_key). Basically, you need to have only one credentials file for a machine.

It will ask for unique environment name like dev, prod, alpha etc. We will use this environment name and deploy our application to AWS Lambda.

Zappa is Configured!

Zappa configured is done, now its time for deploying our application.

zappa deploy dev

Boom, its happening!

Calling deploy for stage dev.. Creating zappatest-dev-ZappaLambdaExecutionRole IAM Role.. Creating zappa-permissions policy on zappatest-dev-ZappaLambdaExecutionRole IAM Role. Downloading and installing dependencies.. Packaging project as zip.. Uploading zappatest-dev-1496245095.zip ( 11 .0MiB ) .. 100 % | ██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ | 11 .5M/11.5M [ 00 :15 & lt ; 00 :00, 751KB/s ] Scheduling.. Scheduled zappatest-dev-zappa-keep-warm-handler.keep_warm_callback! Uploading zappatest-dev-template-1496245132.json ( 1 .6KiB ) .. 100 % | █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ | 1 .61K/1.61K [ 00 :01 & lt ; 00 :00, 1 .23KB/s ] Waiting for stack zappatest-dev to create ( this can take a bit ) .. 75 % | ████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▎ | 3 /4 [ 00 :10 & lt ; 00 :05, 5 .48s/res ] Deploying API Gateway.. Deployment complete!: https://1kfcddadada79nh5.execute-api.us-west-2.amazonaws.com/dev

Done! Our application is now deployed to AWS Lambda. if you wish to make any changes to the application, after changing it you need to update the zappa environment too. To update the environment, type

zappa update dev

Watch Out!

When you open the link provided by API Gateway raises an exception. This is because we didn't set ALLOWED_HOSTS in the Django settings file. However, we will never know while developing since the URL is generated after deploying the application.

Neccessary changes to me made!

Copy the domain name or hostname provided by API gateway and set ALLOWED_HOSTS to that value. After completing this, update the Zappa environment using the command specified above.

zappa update dev

Database Connections

For this application, we will create a new AWS RDS of type mysql. To create an instance follow this link,

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html

Now, you need to change the settings of Django application to use the MySQL AWS RDS. Update the DATABASES in settings file with the following,

DATABASES = { 'default' : { 'ENGINE' : 'django.db.backends.mysql' , 'NAME' : <NAME OF DATABASE>, 'USER' : <RDS_USERNAME>, 'PASSWORD' : <RDS_PASSWORD>, 'HOST' : <RDS_HOSTNAME>, 'PORT' : <RDS_PORT>, } }

Once DATABASES part is updated in the settings file, update the Zappa environment and that's it. Your application now uses AWS RDS you have just created.

I hope the article was of help. Do mention in comments, as to what would you like to hear more about.