Open In App

How to Deploy Django Application in AWS Lambda?

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
Virtual Environment Setup

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.

Python3




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 using Zappa

Deploy Django Application

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 Django Migrations

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.

Deploy Static Files to S3

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 Zappa Deployment

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>
Delete the deployment

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads