You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -10,16 +10,9 @@ This is a Django reference project showing how to develop and deploy Django appl
10
10
11
11
## tl;dr
12
12
13
-
This project implements a simple blog app using vanilla Django function-based views and class-based views as well as DRF function and class-based views. There is also an implementation of the same application using GraphQL. The application involves a simple data model including users, posts with text and image and post likes. Local development using virtual environments and docker are both covered in detail, including guidance on how to run the application on different operating systems (Linux, Intel Mac, M1 Mac, Windows, WSL). There is 100% test coverage for the project and comprehensive e2e tests using Cypress.
13
+
This project implements a simple blog app using vanilla Django function-based views and class-based views as well as DRF function and class-based views. There is also an implementation of the same application using GraphQL. The application involves a simple data model including users, posts with text and image and post likes.
14
14
15
-
Deployment to AWS environment on Elastic Container Service (ECS) is shown with both:
16
-
17
-
- CDK and [a CDK construct library that I wrote specifically for deploying containerized Django projects on AWS](https://github.com/briancaffey/django-cdk)
18
-
- Terraform using [`terraform-aws-django`](https://github.com/briancaffey/terraform-aws-django)
19
-
20
-
This project is originally designed as a reference or example project that I can use when I need to recall common patterns, syntax and frequently-used code snippets. I have tried to carefully document each part of the development process as a guide for someone who wants to learn how this project is built and deployed from the ground up. Please visit the project documentation site ([briancaffey.github.io/django-step-by-step/](https://briancaffey.github.io/django-step-by-step/)) for a complete explanation of the project, step-by-step.
21
-
22
-
This project is open-source and newcomers to Django and Python and welcome to create issues and pull requests.
15
+
This project is designed as a reference or example project that demonstrates common patterns, syntax and frequently-used code snippets. This project is open-source and newcomers are welcome to create issues and pull requests.
23
16
24
17
## Core application
25
18
@@ -30,8 +23,6 @@ This project implements a simple microblogging application called μblog. Here a
30
23
- Signed-in users can like posts
31
24
- Signed-in users can edit and delete their own posts
32
25
33
-
## Implementation
34
-
35
26
μblog's core microblogging application is implemented in 5 different ways:
36
27
37
28
- Django function-based views
@@ -48,26 +39,17 @@ Django templates and Bootstrap are used for the function and class based Django
48
39
49
40
This project is heavily focused on the process of setting up the development environment. This project has been tested and developed on:
50
41
51
-
- Ubuntu 20.04
52
-
- macOS 11.4 (Apple Silicon)
53
-
- Windows 10 (WSL + Docker Desktop)
54
-
55
-
Windows 10 PowerShell development environment is still WIP. Here are some important features of the local development environment:
42
+
- Ubuntu 24.04
43
+
- macOS Sequoia 15.4 (Apple Silicon)
44
+
- Windows 11 (WSL + Docker Desktop)
56
45
57
46
### Makefile
58
47
59
48
A Makefile is included in the root of the project to document. This file helps to document each step of the local development environment and deployment process.
60
49
61
50
### Python dependencies
62
51
63
-
This project's Python dependencies are managed with poetry. Poetry dependencies and dev-dependencies are specified in `pyproject.toml`. These dependencies are exported to two files:
64
-
65
-
-`requirements.txt`: This contains only the dependencies that are required by the project for running in production
66
-
-`requirements_dev.txt`: This contains all the dependencies that are required for running in production and for local development
67
-
68
-
### Developing with virtual environments
69
-
70
-
The application can be developed with a virtual environment locally. This requires starting postgres and redis services locally. Alternatively, postgres, redis and other supporting services can be started with a docker-compose file that exposes the services on `localhost`.
52
+
Python dependencies are currently managed with Poetry.
71
53
72
54
### Developing with docker
73
55
@@ -83,180 +65,29 @@ The docker-compose file contains the following services:
83
65
- celery_worker: celery worker that processes the default queue
84
66
- celery_beat: celery process that queues tasks on a schedule
85
67
- mailhog: a local SMTP server for testing
68
+
- nuxt
69
+
- nginx (allows or the backend and frontend to both run on `localhost` during development)
86
70
87
-
The application can also run locally inside a local Kubernetes cluster. This is made possible with minikube. cdk8s and pulumi are both used to show how kubernetes manifest files can be generated dynamically from code (TypeScript) and deployed to a cluster.
88
-
89
-
### e2e testing with Cypress
90
-
91
-
Cypress is used for e2e testing which can run locally against the docker-compose development environment. To test user registration and email verification in e2e tests, MailHog and the MailHog API are used to retrieve the email confirmation link from the email sent by the Django application.
92
-
93
-
## Continuous Integration
94
-
95
-
Multiple tools are used for running unit tests and code quality checks on each commit. These include:
96
-
97
-
- GitHub Actions
98
-
- GitLab CI
99
-
- Bitbucket Pipelines
71
+
## Continuous Integration with GitHub Actions
100
72
101
73
Continuous integration checks that all unit tests pass and that code is formatted correctly. Unit tests run the Python code in a simulated environment that contains the dependent services (postgres and redis). The following tools are used in CI:
102
74
103
75
- flake8
104
76
- black
105
-
- pytest
77
+
- pytest tests
106
78
107
79
## Deployment
108
80
109
-
This project focuses on deployment to AWS using Elastic Container Service.
110
-
111
-
### AWS ECS
112
-
113
-
ECS is my preferred way of running containerized web applications on AWS. To help document best practices for deploying Django applications on ECS, I wrote a reusable CDK construct library that handles infrastructure provisioning for typical deployment scenarios. This project can be found [here](https://github.com/briancaffey/django-cdk).
114
-
115
-
The Django ECS construct included in the library creates the following AWS resources:
116
-
117
-
- VPC (public, private and isolated subnets, NAT Gateways, routing tables, Internet Gateway, etc)
118
-
- S3 bucket for storing static files and media files
119
-
- ECS Cluster (a grouping of ECS resources)
120
-
- ECS tasks and services for various components of the application (web, celery workers, management commands and tasks)
121
-
- A docker image built from our Django application code and specified Dockerfile
122
-
- Application Load Balancer
123
-
- TLS certificate that can attached to the Application Load Balancer terminating SSL/TLS
124
-
- A Route53 DNS record that points to the Application Load Balancer public DNS name
125
-
- AWS RDS Postgres database instance that servers as the database for the Django application
126
-
- A single-node AWS ElastiCache Redis cluster that provides caching and messaging brokering for celery workers
127
-
- Security groups that allow for the stateless application layer to communicate with the Postgres database and Redis cluster
128
-
- Automated database migrations for the Django application using ECS tasks
81
+
This project focuses on deployment to AWS using Elastic Container Service. This project has three related repositories for setting up AWS resources using Infrastructure as Code using some of the popular IaC tools: Terraform, Pulumi and CDK:
129
82
130
-
The Django ECS construct takes a few inputs, including:
- The path to the Dockerfile that defines the main image used for the Django application
134
-
- The domain name in Route53 that will be used to generate DNS records in your account
135
-
- Optionally provide the ARN of an ACM certificate to be attached to the Application Load Balancer
136
-
- A list of strings to be used as the command for the web service
137
-
- A list of strings to be used as the command for the celery workers
138
-
- A list of strings to be used as the command for the celery beat process
87
+
These repositories each contain a reusable library that can be used to deploy nearly the same set of AWS resources for running this Django + Nuxt application. There also GitHub Actions workflows for creating, updating and deleting AWS resources using these libraries and related tools. See `.github/workflows/iac_{terraform,pulumi,cdk}_actions.yml`.
139
88
140
-
141
-
This project can deploy ECS from the command line (using `make cdk-deploy`) or from a CI/CD pipeline. GitHub Actions and GitLab CI both include pipeline stages that deploy the application to AWS ECS.
142
-
143
-
Additional [ECS Exec](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/) is used to run management commands and open shells inside of the containers running on Fargate.
89
+
For application updates there is a workflow in `.github/workflows/cd_app_update.yml` that can update a new version of the Django and Nuxt applications. This workflow can work with any of the three IaC libraries mentioned above.
144
90
145
91
## This project is open source and MIT Licensed
146
92
147
93
See [LICENSE.md](/LICENSE.md)
148
-
149
-
## 12 Factor App
150
-
151
-
This project tries to follow the [12 Factor App](https://12factor.net/) principles. Here are the 12 factors of the 12 Factor app with a brief description of how they are achieved in this project across multiple deployment environments.
152
-
153
-
### I: Codebase
154
-
155
-
The code can be found in multiple public repositories:
156
-
157
-
> One codebase tracked in revision control, many deploys
158
-
159
-
-**GitHub** (please open any issues, pull requests or discussions here): [https://github.com/briancaffey/django-step-by-step](https://github.com/briancaffey/django-step-by-step)
160
-
161
-
### II: Dependencies
162
-
163
-
There are a few different ways in which this project manages dependencies:
164
-
165
-
-`poetry` manages Python dependencies
166
-
-`npm` manages TypeScript/JavaScript dependencies for the construct library application
167
-
- The `Dockerfile` defines dependencies needed for the container, including the version of Python to use
168
-
- The `django-cdk` library defines specific version of AWS services to use, such as the version of postgres and Redis that are used
169
-
-`terraform-aws-django` also defines specific versions, such as the database engine version to use for Postgres
170
-
171
-
### III: Config
172
-
173
-
There is a good amount of environment variables used for configuration both locally and in the different production environments.
174
-
175
-
Locally, the application uses default values that allow development in a virtual environment to work without the need for configuring any environment variables as a separate step.
176
-
177
-
For example, Postgres is configured with the following default values in the Django application:
The `django-cdk` application uses environment variables to determine which options to use for deployment. For example, the `HostedZoneName` is read in from the environment and use to determine which DNS records and ACM records to create. CloudFormation Stacks help to isolate environments, and no infrastructure is shared between environments.
193
-
194
-
> A litmus test for whether an app has all config correctly factored out of the code is whether the codebase could be made open source at any moment, without compromising any credentials.
195
-
196
-
This is another important point from the 12 Factor App principles that is true for this project.
197
-
198
-
One interesting part about config is the Postgres password for the ECS environment. The ECS environment uses an AWS Secrets Manager `Secret` to store the database password information, including the password, in a JSON string.
199
-
200
-
The name of this `Secret` is passed as an environment to the Django application, and the Django application uses another library to retrieve and cache the database password for later use. Again, the value of the secret is not passed to Django as an environment variable, but the name of the `Secret` (from AWS Secrets Manager) is the value passed. This way we don't even have to worry about what the password is. It is not stored in the code base and it is not even stored anywhere in config (until is created in AWS Secrets Manager).
201
-
202
-
### IV: Backing Services
203
-
204
-
In AWS, it is easy to start relying on AWS services such as RDS, ElastiCache, S3 and other services.
205
-
206
-
### V: Build, release, run
207
-
208
-
This step in the 12 Factor App is where CDK really shines. The `cdk deploy` command builds, releases and runs the application in one command. First, it is important to note that CDK uses something called `DockerImageAsset`, which allows us to point to the directory and Dockerfile of an application that we want to build and push to a docker registry. To use this feature, we must first run `cdk bootstrap` once in our AWS account. This will create the ECR registry that any `DockerImageAsset` will be pushed to.
209
-
210
-
When `cdk deploy` runs, it first builds and pushes the docker image to the ECR registry created by the `cdk bootstrap` command. `cdk deploy` then proceeds to create or update the AWS resources defined in the construct. Another advantage of CDK is automatic rollbacks.
211
-
212
-
### VI: Processes
213
-
214
-
> Execute the app as one or more stateless processes
215
-
216
-
In each environment, both local and non-local, the application's processes are clearly defined.
217
-
218
-
The CDK construct is passed a list of strings that define the processes that are run in the container for the wep services as well as the celery worker and celery beat processes.
219
-
220
-
### VII: Port binding
221
-
222
-
This is done in ECS.
223
-
224
-
### VIII: Concurrency
225
-
226
-
> The array of process types and number of processes of each type is known as the process formation.
227
-
228
-
The ECS construct has a simple process formation: web service that scales up and down between a minimum and maximum number of instances. Celery workers that scale between a minimum and maximum number of instances, and a single celery beat process.
229
-
230
-
### IX: Disposability
231
-
232
-
Using CDK is a great way to put application disposability into practice. ECS services make sure that some number of ECS Tasks are running at a given point in time. If we go into the AWS console and delete a task, it will be started again almost instantly.
233
-
234
-
### X: Dev/prod parity
235
-
236
-
This project makes dev/prod parity somewhat trivial. Using Infrastructure as Code, we can be confident that two environments will only vary by the values that are passed in through environment variables. If the only difference between two application stacks is the subdomain, then we can expect that everything else about the two applications is similar and that none of the other resources between the two environments will be shared.
237
-
238
-
### XI: Logs
239
-
240
-
CloudWatch is a great tool for monitoring logs and getting observability with minimal effort.
241
-
242
-
### XII: Admin processes
243
-
244
-
> Run admin/management tasks as one-off processes
245
-
246
-
Developers will often wish to do one-off administrative or maintenance tasks for the app, such as:
247
-
248
-
- Running database migrations
249
-
- Running a console
250
-
- Running one-time scripts committed into the app’s repo
251
-
252
-
With ECS and CDK, management commands can be run easily either through automation or using a tool called ECS Exec.
253
-
254
-
To run automated tasks, `managementCommandProps` can be passed a value of `true` (`false` by default). This will run the task each time the application is deployed with `cdk deploy`. This uses the AWS Custom Resource that is defined in the construct. The CR's `onCreate` and `unUpdate` are set to an `AwsSdkCall` that runs `ecs:RunTask` with the appropriate parameters.
255
-
256
-
If you do not want to run database migrations automatically as a Custom Resource in CDK, you can use the AWS CLI to run the command from your CI tool, or you can use ECS Exec.
257
-
258
-
ECS Exec would also be a good choice if you want to run a one-time script or open a console in the container.
259
-
260
-
## Unit Testing backend Django application with GitHub Actions
261
-
262
-
Backend tests for the Django application run when code is pushed to the `dev` branch.
0 commit comments