Serverless Django with Zappa and AWS Lambda

Aug. 20, 2020, 3:02 p.m.

Django Serverless · 5 min read

Serverless Django with Zappa and AWS Lambda

What is Serverless?

Lately serverless computing has enjoyed a surge of popularity.  Unlike deploying a Django application on an EC2 on AWS or a Droplet on Digital Ocean, deploying a serverless application involves calling on-demand functions instead of passing requests through a dedicated server.  For example, normally when a user visits a website powered by a Django web application, all requests pass through a server running 24/7.  However, a serverless application handles requests by activating a dormant function with all computing resources managed automatically.  This results in both lower maintenance time and cost, therefore making the serverless approach exceedingly scalable. Given these benefits, newer startups have adopted a serverless approach to grow and scale as efficiently as possible.

 

Serverless Framework and Providers

First introduced in 2015, the serverless framework is an open-source web framework originally developed for launching applications on AWS Lambda.  AWS Lambda is a serverless computing platform for functions as a service (FaaS).  While AWS Lambda was one of the earlier FaaS platforms, other large tech companies have expanded into the field with their own respective offerings:

  • AWS Lambda
  • Google Cloud Platform
  • IBM Cloud Functions
  • Azure Functions (Microsoft)

For various examples of using the serverless framework, visit the official site where you'll find tutorials on Twilio call forwarding, scheduling a cron job, setting up a Telegram bot, and many more.  For this tutorial, we will focus on combining Django and serverless to get the best of both worlds.

 

Serverless and Django

At first, serverless and Django may seem at odds.  With serverless architecture, developers can simply write functions for specific requests instead of going through the trouble of setting up a Django project.  This is absolutely true, but if you are interested in still using Django's many pre-built features such as its database queries, you might want to deploy a serverless Django application.  With this approach, each request will start a function that boots up the Django project.  To accomplish this, we also need Zappa, which will allow us to easily deploy our Django application on AWS Lambda with only a few commands.  

 

Setup AWS Credentials on your Machine

If you have never used the AWS command-line interface, you will likely need to set up AWS credentials.  After creating an IAM user to get an access key id and secret key, create a folder on your local machine and add your keys in the following format.  We will need this information to connect to the AWS API gateway.

  • Create AWS credentials folder
    • ~/.aws/credentials on Linux, macOS, or Unix

    • C:\Users\USERNAME\.aws\credentials on Windows

  • Add credentials
    • [default]
      aws_access_key_id = your_access_key_id
      aws_secret_access_key = your_secret_access_key

 

Create a Virtual Environment and Django Project

By now, you should be familiar with creating a virtual environment and starting a new Django project.  Refer to creating a virtual environment if you need additional help.  Note, Zappa seems to be incompatible with the latest version of Django, 3.1, so we will install version 2.1.5.

Windows:

C:\Users\Owner\Desktop\code>py -m venv env
C:\Users\Owner\Desktop\code>cd env

C:\Users\Owner\Desktop\code\env>Scripts\activate

(env) C:\Users\Owner\Desktop\code\env>pip install django==2.1.5

(env) C:\Users\Owner\Desktop\code\env>django-admin startproject mysite

 

Install and Initialize Zappa

(env) C:\Users\Owner\Desktop\code\env>cd mysite

(env) C:\Users\Owner\Desktop\code\env\mysite>pip install zappa

(env) C:\Users\Owner\Desktop\code\env\mysite>zappa init

 

Zappa will ask a variety of questions to configure your project.  First, name your environment, select your AWS credentials you previously created, and create a new S3 bucket. We'll name our project 'dev', select our default credentials, and create a new S3 bucket.

███████╗ █████╗ ██████╗ ██████╗  █████╗
╚══███╔╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗
  ███╔╝ ███████║██████╔╝██████╔╝███████║
 ███╔╝  ██╔══██║██╔═══╝ ██╔═══╝ ██╔══██║
███████╗██║  ██║██║     ██║     ██║  ██║
╚══════╝╚═╝  ╚═╝╚═╝     ╚═╝     ╚═╝  ╚═╝

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'): dev

AWS Lambda and API Gateway are only available in certain regions. Let's check to make sure you have a profile set up in one that will work.
We found the following profiles: eb-cli, and default. Which would you like us to use? (default 'default'):

Your Zappa deployments will need to be uploaded to a private S3 bucket.
If you don't have a bucket yet, we'll create one for you too.
What do you want to call your bucket? (default 'zappa-c10y6avdv'):

 

Next, Zappa will recognize that the project is indeed a Django application and locate the path to your settings file. Since we named our project mysite, our path is by default mysite.settings.  Press enter to continue with the default option.  Zappa will then ask if you want to deploy on all available regions.  Given that this is just a demo, select "no" and finally confirm your settings.  Zappa will present you with a command to deploy your project, which we will use next.

It looks like this is a Django application!
What is the module path to your projects's Django settings?
We discovered: mysite.settings
Where are your project's settings? (default 'mysite.settings'):

You can optionally deploy to all available regions in order to provide fast global service.
If you are using Zappa for the first time, you probably don't want to do this!
Would you like to deploy this application globally (default 'n') [y/n/(p)rimary]: n

Okay, here's your zappa_settings.json:

{
    "dev": {
        "aws_region": "us-west-2",
        "django_settings": "mysite.settings",
        "profile_name": "default",
        "project_name": "mysite",
        "runtime": "python3.7",
        "s3_bucket": "zappa-c10y6avdv"
    }
}

Does this look okay? (default 'y') [y/n]: y

Done! Now you can deploy your Zappa application by executing:

        $ zappa deploy dev

After that, you can update your application code with:

        $ zappa update dev

To learn more, check out our project page on GitHub here: https://github.com/Miserlou/Zappa
and stop by our Slack channel here: https://slack.zappa.io

Enjoy!,
 ~ Team Zappa!

 

Deploy

zappa deploy dev

Check out the website at the URL provided after you deploy.  You'll receive an error since we need to add this new address to our ALLOWED_HOSTS in mysite/settings.py.

Open mysite/settings.py and add your URL to ALLOWED_HOSTS:

ALLOWED_HOSTS = ['6902izxesc.execute-api.us-west-2.amazonaws.com/dev']

Then update the project with the following command.

zappa update dev

Since we do not have a path in our project for "/dev" you might still encounter an error.  Simply add "/admin" at the end of the URL to check if the admin page renders.  It should appear but without any CSS since static files are not setup.

Note: To get access to static files, you will need to configure your project to use an S3 bucket.  Follow our guide here.  Feel free to use the same bucket we created for this project instead of creating an entirely new bucket.  Once configured, run Zappa update dev again.  To add a database, use AWS RDS and ensure the capacity type is set to "Serverless".  Check out this tutorial to add a database.  In production make sure, DEBUG is set to False and environment variables are configured to handle any sensitive information.  

 

Undeploy

Enter the following command to remove the API gateway and Lamda function you previously created.

zappa undeploy dev

 

 

 

 


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments