Pre-requisite: AWS , Python
Django is a Python web framework that makes it easy to build web applications quickly and securely. It has a large and helpful community that provides support and contributes to its development.
AWS Lambda is a serverless computing platform that runs your code in Docker containers, provides us with the best possible speed, and there is a number of third-party apps, and tools that make Lambda usage much easier, in this tutorial we gonna use one such tool.
.jpg)
Django Application Deployment using AWS Lambda
Why We Choose AWS Lambda
There are several reasons why we choose AWS Lambda over other choices like AWS EC2, Elastic Bean Stalk, etc for deploying our Django application:
- Cost-Effective : AWS Lambda is a cost-effective option when compared to other services we’ve.
- Integration with Other AWS Services : AWS Lambda has support for various other AWS services, we can integrate them easily such as API Gateway, Event bridge, etc, which makes it easy to deploy.
- No Server Management : With AWS Lambda, we don’t have to worry about managing the infrastructure, as AWS takes care of it for us. and we going to use Zappa for deploying our Django application to AWS Lambda.
Zappa
Zappa is a serverless framework for deploying python applications using AWS Lambda and API Gateway. Zappa helps us to manage our Django applications easily and provides a convenient way to keep your deployments up-to-date. Zappa has a large and active community that provides support and contributes to its development, making it a great choice for deploying your Django applications.
Prerequisites:
To follow this tutorial, you will need the following:
- AWS account
- Basic knowledge of AWS Lambda, API Gateway, and Django
- Python3 and venv module installed on your local machine
Setting up a Django Project
1. Create and activate a Virtual environment for this Django project (ignore if already have one)
Note: You can refer to the application code in the GitHub repository
python3 -m venv myvenv
source myvenv/bin/activate
-(1)-1024.png)
Create Virtual Environment
2. Install all the requirements for this project and store the requirements in requirements.txt , if you didn’t have requirements documented, you can run the below command to get installed requirements details into a file.
pip freeze > requirements.txt
3. Add Zappa to requirements
echo "zappa" >> requirements.txt
4. Make sure all the requirements are installed, by running the below command.
pip install -r requirements.txt
Initialize Zappa
1. In your Django project’s root directory, run the following command:
zappa init
and follow the prompts to configure your Zappa deployment.
(myvenv) coder@DilLip:/home/dillipchowdary/GFGArticles/Django-Sample-Project$ zappa init
███████╗ █████╗ ██████╗ ██████╗ █████╗
╚══███╔╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗
███╔╝ ███████║██████╔╝██████╔╝███████║
███╔╝ ██╔══██║██╔═══╝ ██╔═══╝ ██╔══██║
███████╗██║ ██║██║ ██║ ██║ ██║
╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝
Welcome to Zappa!
...
Your Zappa configuration can support multiple production
stages, like 'dev', 'staging', and 'production'.
What do you want to call this environment (default 'dev'):
...
...
Where are your project's settings?: todo.settings.prod
...
Would you like to deploy this application globally?
(default 'n') [y/n/(p)rimary]: n
Okay, here's your zappa_settings.json:
{
"dev": {
"django_settings": "todo.settings.prod",
"project_name": "django-sample-project",
"runtime": "python3.9",
"s3_bucket": "alpha-common-bucket"
}
}
Configure Database
For local development, we can use SQLite, but in general, it’s better to use MySQL server for better performance in large-scale applications, here in this case we used AWS RDS as a DB server.
MySQL in Lambda?
By default, AWS Lambda will not have MySQL, either we have to add custom compiled binary or use existing public lambda layers or we can also use certain python packages to add MySQL support to our Application.
Here in this project, we’re using 3rd approach, and using pymysql , which is a python package that helps us to connect to MySQL DB with ease, to configure our project with pymysql, add the below code snippet in Django settings, here we’ve added this under settings/__init__.py .
The below snippet makes Django ORM use pymysql without any code changes needed.
Python
import pymysql
pymysql.install_as_MySQLdb()
Have a look at the Database config in todo/settings/prod.py > DATABASES variable.
I recommend you use environment variables for confidential data, and also it can be easily configurable for different environments.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.getenv("SQL_DB_NAME"),
'USER': os.getenv("SQL_DB_USERNAME"),
'PASSWORD': os.getenv("SQL_DB_PASSWORD"),
'HOST': os.getenv("SQL_DB_HOST"),
'PORT': os.getenv("SQL_DB_PORT"),
}
}
Setup Static Files Hosting
Static files are essential files that don’t need any dynamic changes, like static HTML, CSS, js, fonts, etc.
It’s best practice to host static files from another source and not include them in the application bundle itself.
You can have a look at the Static Files Hosting config in todo/settings/prod.py.
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
USE_S3 = bool(os.environ.get("USE_S3_STATIC", "False"))
if USE_S3 is True:
AWS_ACCESS_KEY_ID = os.environ.get("CUSTOM_AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("CUSTOM_AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
else:
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
Deploy Application
We are all set for deployment, we configured our app with the required things, and now we can deploy our application to AWS Lambda.
Here the below command will bundle your application along with your project requirements and deploy it in AWS Lambda.
zappa deploy <stage>
The above command will create a Lambda function with our Django application code and integrates it with API Gateway so that we can invoke the Django API.
Note: You can ignore the below warning after deployment, as it was caused due to, environment variables haven’t been set for our application yet.
-(1).png)
Deploy Django Application
While deploying a Django app to AWS Lambda is a great skill, mastering deployment alongside other Django capabilities can take your development skills to the next level. If you’re looking to delve further into Django, the Complete Django Web Development Course – Basics to Advance course provides comprehensive coverage of advanced topics.
Update Environment Variables
Make sure you set the proper environment variables required for deployment in set_env_vars.py , and run it after deploying the application to set env vars for your application. After updating the env vars in set_env_vars.py Run the below command to set/update env variables for our application.
python set_env_vars.py
Post-Deployment Steps
We’ve deployed the application in Lambda now, but still, there are a few more things to do, here we interact with production entities directly.
Configure the local system to interact with the production
To interact with the production deployment, we need to configure our local environment, like settings environment variable DJANGO_SETTINGS_MODULE (todo.settings.prod), and also other required environment variables.
Create a file with the name env_vars.sh in the project home directory with the below content (update values appropriately)
export DJANGO_SETTINGS_MODULE=todo.settings.prod
export SECRET_KEY=mys3cr3tkey
export SQL_DB_NAME=my_db_name
export SQL_DB_USERNAME=my_db_username
export SQL_DB_PASSWORD=TLQahsnbKAF9sOmI
export SQL_DB_HOST=example.com
export SQL_DB_PORT=3306
export USE_S3_STATIC=True
export CUSTOM_AWS_ACCESS_KEY_ID=ABCDEDFGHIJKL
export CUSTOM_AWS_SECRET_ACCESS_KEY=abcdefghijkl
export AWS_STORAGE_BUCKET_NAME=my-storage-bucket
Then run the below command to set those environment variables, so that further commands will make use of these commands.
source env_vars.sh
Apply Migrations
Run the below command to apply migrations, these migrations will be applied in the DB server we configured in environment variables.
-1024.jpg)
Apply Database Migrations
Deploy Static files
Run the below command to push required static (HTML templates, CSS, js, images, ) files to the AWS S3 Bucket .
-1024.jpg)
Collect required static files to S3
Access Application
You can now access your application by using the URL shown in the deployment.
Update Deployment
We can use the below command if we wanna update our existing deployment.
zappa update <stage>
-(1)-1024.png)
Update Django Application Deployment
Delete Deployment
If you wanna delete your deployed application, run the below command, which will remove all the entities created for this deployment.
zappa undeploy <stage>
-(1).png)
Undeploy Django Application
Conclusion: In this article, we showed you how to deploy a Django application using Zappa. Zappa makes it easy to deploy and manage your Django applications on AWS Lambda and API Gateway and provides a convenient way to keep your deployments up-to-date. Whether you’re just starting out with Django or looking to scale your existing application, deploying with Zappa is a great option.
Similar Reads
How to Deploy Django Application in AWS EC2?
In this article, we will study how we can deploy our existing Django web application to Windows Server in AWS EC2. We will also see how to use the public IP of the EC2 instance to access the Django application. For this article, you should know about setting up EC2 in AWS. We will see how to deploy
3 min read
How to Deploy a Django Application in Kubernetes
In this article, we will study how we can deploy Django web applications to Kubernetes. We will also see how to dockerize and build an image of the Django application using Dockerfile. For this article, you should know about setting up a VM in Azure. We will see how to deploy applications on Linux S
5 min read
How To Deploy Python Application In AWS?
In this article, we will explore how one as a Python developer can deploy the application by harnessing the capabilities of AWS. AWS, a leading cloud computing platform, offers a wide range of services to help developers build, deploy, and manage applications at scale EC2. It provides scalable compu
4 min read
Deploy an ASGI Django Application
ASGI, which stands for Asynchronous Server Gateway Interface, is a big deal in Django. It basically helps Django handle lots of things at once, like requests from users. Instead of waiting for one thing to finish before starting the next, ASGI lets Django do multiple tasks simultaneously. It's like
5 min read
Django Web Application Deployment On AWS EC2 With Windows Server
In this article, we will study how we can deploy our existing Django web application to Windows Server in AWS EC2. We will also see how to use the public IP of the EC2 instance to access the Django application. For this article, you should have knowledge about setting up EC2 in AWS. So let's proceed
4 min read
Deploy a React Application with AWS
AWS is a subsidiary of Amazon & offers a broad range of cloud computing services, which means services using their infrastructure which is hosted on various data centers all over the world which we can rent to run our own solutions. In this article, we will learn how to deploy a React applicatio
4 min read
How to Deploy a Web Application on GCP?
Google Cloud Platform is one of the cloud service providers that provide various cloud services for a seamless experience. It provides various services like storage, networks, development tools, Analytics tools, infrastructure, and many more. Benefits Of Deploying Web Applications on Google Cloud Pl
4 min read
How To Deploy Django In Azure ?
In this tutorial, we'll deploy the Python (Django) Web app to Azure. Microsoft Azure provides an environment for websites to be deployed, managed, and scaled very easily. We'll see two options to deploy our Django website - one using Azure CLI and the other using Azure Portal's Interface. The deploy
7 min read
Deploy a Spring Boot Application with AWS
A spring boot application is a Java-based web application that is built using the Spring Boot framework. Spring Boot is a project designed to simplify the development and deployment of production-ready Java applications. Creating a Spring Boot Project with Spring Initializr: Step-by-Step GuideNote :
5 min read
How To Deploy a Django Application to Heroku with Git CLI?
Deploying a Django application to Heroku using the Git command-line interface (CLI) is a simple process. Heroku provides a platform-as-a-service (PaaS) that enables you to deploy, manage, and scale your applications easily. This guide will walk you through the steps to deploy your Django application
3 min read