Skip to content

Commit

Permalink
added django
Browse files Browse the repository at this point in the history
  • Loading branch information
Two-Trick-Pony-NL committed Oct 12, 2023
1 parent eb772d3 commit a589bc5
Show file tree
Hide file tree
Showing 17 changed files with 390 additions and 0 deletions.
115 changes: 115 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
name: 🚀 Deployment
# Only trigger, when the build workflow succeeded
on:
push:
branches: [ "main" ]
permissions:
contents: read

env:
AWS_REGION: ${{ secrets.AWS_REGION }}
AWS_LIGHTSAIL_SERVICE_NAME: ${{ secrets.AWS_SERVICE_NAME }}
concurrency:
group: '${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}'
cancel-in-progress: true
jobs:

buildnginx:
name: 🌎 building nginx webserver
runs-on: ubuntu-latest
steps:
- name: 🗂 Getting code from Github
uses: actions/checkout@v2
- name: ⚙️ Updating to the latest versions
run: |
sudo apt-get update
sudo apt-get install -y jq unzip
- name: 🏢 Install Amazon Client
run: |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install || true
aws --version
curl "https://s3.us-west-2.amazonaws.com/lightsailctl/latest/linux-amd64/lightsailctl" -o "lightsailctl"
sudo mv "lightsailctl" "/usr/local/bin/lightsailctl"
sudo chmod +x /usr/local/bin/lightsailctl
- name: 🤐 Log in to AWS Lightsail with Secrets
uses: aws-actions/configure-aws-credentials@v1
with:
aws-region: ${{ env.AWS_REGION }}
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: 🐳 Create a Docker Container for NGINX
run: docker build -t nginx:latest -f ./AWS/nginx/Dockerfile .
- name: 📬 Upload NGINX image to AWS container register
run: |
service_name=${{ env.AWS_LIGHTSAIL_SERVICE_NAME }}
aws lightsail push-container-image \
--region ${{ env.AWS_REGION }} \
--service-name ${service_name} \
--label nginx \
--image nginx:latest
- name: =========== All done. Cleaning up ♻️ ===========
run: ls

builddjango:
name: 🚨 Deploying
runs-on: ubuntu-latest
steps:
- name: 🗂 Getting code from Github
uses: actions/checkout@v2
- name: ⚙️ Updating to the latest versions
run: |
sudo apt-get update
sudo apt-get install -y jq unzip
- name: 🏢 Install Amazon Client
run: |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install || true
aws --version
curl "https://s3.us-west-2.amazonaws.com/lightsailctl/latest/linux-amd64/lightsailctl" -o "lightsailctl"
sudo mv "lightsailctl" "/usr/local/bin/lightsailctl"
sudo chmod +x /usr/local/bin/lightsailctl
- name: 🤐 Log in to AWS Lightsail with Secrets
uses: aws-actions/configure-aws-credentials@v1
with:
aws-region: ${{ env.AWS_REGION }}
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: 🤐 Make envfile
uses: SpicyPizza/create-envfile@v1.3
with:
envkey_DB_USER: ${{ secrets.DB_USER }}
envkey_DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
envkey_DB_HOST: ${{ secrets.DB_HOST }}
envkey_DB_NAME: ${{ secrets.DB_NAME }}
envkey_DB_PORT: ${{ secrets.DB_PORT }}
envkey_S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
envkey_S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
envkey_S3_AWS_STORAGE_BUCKET_NAME: ${{ secrets.S3_AWS_STORAGE_BUCKET_NAME }}
envkey_SECURE_SETTINGS: True
envkey_DEBUG: false
directory: core
file_name: .env
fail_on_empty: false
- name: Installing dependancies
run: |
sudo pip3 install --upgrade pip
sudo pip3 install -r requirements.txt
- name: 🐳 Create a Docker Container for DJANGO
run: docker build -t countdowntimer:latest .
- name: 📬 Upload Backend image to AWS container register
run: |
service_name=${{ env.AWS_LIGHTSAIL_SERVICE_NAME }}
aws lightsail push-container-image \
--region ${{ env.AWS_REGION }} \
--service-name ${AWS_LIGHTSAIL_SERVICE_NAME} \
--label countdowntimer \
--image countdowntimer:latest
- name: 🚀 Launching the Containers
run: |
aws lightsail create-container-service-deployment --service-name ${{ env.AWS_LIGHTSAIL_SERVICE_NAME }} \
--containers file://AWS/deploymentconfig.json \
--public-endpoint file://AWS/publicendpoint.json
9 changes: 9 additions & 0 deletions AWS/deploymentconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{"countdowntimer": {
"image": ":countdowntimer.countdowntimer.latest",
"ports": {"8000": "HTTP"}
},
"countdowntimer-nginx": {
"image": ":countdowntimer.nginx.latest",
"ports": {"80": "HTTP"}
}
}
17 changes: 17 additions & 0 deletions AWS/nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# This needs to be run from the root directory as you want to call files from mapmaker/static
# to do so use this build command:
# docker build -t nginx:latest -f Infrastructure/nginx/Dockerfile .

FROM nginx:1.19.0-alpine
# Adding temp file for cache
RUN mkdir /tmp/nginx

#Adding Django Static files into nginx so they dont have to be answered by Django
COPY staticfiles/ ./static
COPY staticfiles/ ./staticfiles


#Specific settings so nginx works as a reverse proxy
COPY AWS/nginx/default.conf ./etc/nginx/conf.d/default.conf

EXPOSE 80
25 changes: 25 additions & 0 deletions AWS/nginx/default.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
proxy_cache_path /tmp/nginx keys_zone=mycache:1m;


server {
location / {
#Proxy settings for Django server upstream
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
}
location /healthcheck {
#This is for AWS To hit healthchecks
add_header Content-Type text/plain;
return 200 'Up and running!';
}
location /static/ {
proxy_cache mycache;
proxy_cache_background_update on;
proxy_cache_use_stale updating;
proxy_cache_valid 60s;
alias /static/;
}
}
11 changes: 11 additions & 0 deletions AWS/publicendpoint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"containerName": "countdowntimer-nginx",
"containerPort": 80,
"healthCheck": {
"healthyThreshold": 2,
"unhealthyThreshold": 10,
"timeoutSeconds": 60,
"intervalSeconds": 300,
"path": "/healthcheck",
"successCodes": "200-299"
}}
Empty file added core/__init__.py
Empty file.
Binary file added core/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added core/__pycache__/settings.cpython-312.pyc
Binary file not shown.
Binary file added core/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file added core/__pycache__/wsgi.cpython-312.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions core/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for core project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_asgi_application()
123 changes: 123 additions & 0 deletions core/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 4.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-q#%#qkb-q+z+@ab7p%l%3$+p(5td*x@f+i+_i-vd3957co&c#^'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'core.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
22 changes: 22 additions & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
URL configuration for core project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions core/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_wsgi_application()
Empty file added db.sqlite3
Empty file.
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Loading

0 comments on commit a589bc5

Please sign in to comment.