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.
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
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.
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.
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 .
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>
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>
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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read