From 658753dea4c09f83f6502d95e2e64ffe25eb6592 Mon Sep 17 00:00:00 2001 From: Keannu Bernasol Date: Fri, 30 Aug 2024 15:46:30 +0800 Subject: [PATCH] Clean up imports and .env variables --- .env.sample | 26 +++++++++---- backend/api/urls.py | 4 +- backend/config/settings.py | 77 +++++++++++++++----------------------- backend/payments/views.py | 2 +- 4 files changed, 51 insertions(+), 58 deletions(-) diff --git a/.env.sample b/.env.sample index ef58e7c..8a90ce7 100644 --- a/.env.sample +++ b/.env.sample @@ -1,9 +1,11 @@ # Django -### Use https://djecrety.ir/ for generation! +# Use https://djecrety.ir/ for generation SECRET_KEY = '' # Production Switches BACKEND_DEBUG = 'True' +USE_VAULT = 'False' +SERVE_MEDIA = 'False' # Superuser Credentials DJANGO_ADMIN_USERNAME = 'admin' @@ -23,7 +25,7 @@ EMAIL_USE_TLS = 'False' EMAIL_ADDRESS = 'noreply-testing@drf-template.com' # Database -### Have different credentials set on dev, staging, and prod! +# Have different credentials set on dev, staging, and prod DB_DATABASE = 'drf-template' DB_USERNAME = 'root' DB_PASSWORD = '' @@ -32,7 +34,7 @@ DB_PORT = '5432' DB_SSL_MODE = 'disable' # Redis -### Used for DB cache and Celery broker +# Used for DB cache and Celery broker REDIS_HOST = 'redis' REDIS_PORT = '6379' @@ -44,16 +46,24 @@ CELERY_RESULT_BACKEND = 'redis://redis:6379/0' STRIPE_SECRET_KEY = '' STRIPE_SECRET_WEBHOOK = '' -BACKEND_DOMAIN = 'localhost:8000' -DOMAIN = 'localhost:4200' +USE_VAULT = 'False' +SERVE_MEDIA = 'False' +BACKEND_URL = 'localhost:8000' +FRONTEND_URL = 'localhost:4200' USE_HTTPS = 'False' -DJANGO_PORT = '8000' +TIMEZONE = 'Asia/Manila' + +# Cloud Storage +# No need to set these if you're not using S3 +CLOUD_BUCKET = '' +MEDIA_CONTAINER = '' +STATIC_CONTAINER = '' # Proxy (For Selenium) USE_PROXY = 'False' -## IP-Whitelisted Proxy Address +# IP-Whitelisted Proxy Address PROXY_IP_WHITELIST = 'proxy-here.com:12345' -## Username/Password Proxy Address +# Username/Password Proxy Address PROXY_USER_AUTH = 'username:password@proxy-here.com:12345' # CAPTCHA diff --git a/backend/api/urls.py b/backend/api/urls.py index c59de67..e45f4fd 100644 --- a/backend/api/urls.py +++ b/backend/api/urls.py @@ -1,7 +1,7 @@ from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import path, include -from config.settings import DEBUG, CLOUD, MEDIA_ROOT +from config.settings import DEBUG, SERVE_MEDIA, MEDIA_ROOT urlpatterns = [ path('accounts/', include('accounts.urls')), path('subscriptions/', include('subscriptions.urls')), @@ -11,7 +11,7 @@ urlpatterns = [ ] # URLs for local development -if DEBUG and not CLOUD: +if DEBUG and SERVE_MEDIA: urlpatterns += staticfiles_urlpatterns() urlpatterns += static( 'media/', document_root=MEDIA_ROOT) diff --git a/backend/config/settings.py b/backend/config/settings.py index 5e96c0a..ef6f053 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -1,15 +1,3 @@ -""" -Django settings for test backend 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 datetime import timedelta from pathlib import Path from dotenv import load_dotenv, find_dotenv # Python dotenv @@ -21,17 +9,19 @@ BASE_DIR = Path(__file__).resolve().parent.parent # Root folder where docker-compose.yml is located ROOT_DIR = Path(__file__).resolve().parent.parent.parent -# If you're hosting this on the cloud, have this set -CLOUD = bool(os.getenv('CLOUD', False)) +# If you're hosting this with a secret provider, have this set to True +USE_VAULT = bool(os.getenv('USE_VAULT', False) == 'True') +# Have this set to True to serve media and static contents directly via Django +SERVE_MEDIA = bool(os.getenv('SERVE_MEDIA', False) == 'True') load_dotenv(find_dotenv()) def get_secret(secret_name): - if CLOUD: + if USE_VAULT: try: pass - # Add specific implementations here if deploying to Azure, GCP, or AWS to get secrets + # Add specific implementations here if deploying to Azure, GCP, or AWS to get secrets from vault except: secret_value = "" else: @@ -44,25 +34,18 @@ def get_secret(secret_name): return secret_value -# Frontend Domain -DOMAIN = get_secret('DOMAIN') -# Backend Domain -BACKEND_DOMAIN = get_secret('BACKEND_DOMAIN') # URL Prefixes USE_HTTPS = (get_secret('USE_HTTPS') == 'True') -URL_PREFIX = 'https://' if CLOUD and USE_HTTPS else 'http://' -BACKEND_URL = f'{URL_PREFIX}{BACKEND_DOMAIN}' -FRONTEND_URL = f'{URL_PREFIX}{DOMAIN}' +URL_PREFIX = 'https://' if USE_HTTPS else 'http://' +BACKEND_URL = URL_PREFIX + get_secret('BACKEND_URL') +FRONTEND_URL = URL_PREFIX + get_secret('FRONTEND_URL') ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = [ BACKEND_URL, FRONTEND_URL + # You can also set up https://*.name.xyz for wildcards here ] -if CLOUD: - # TODO: If you require additional URLs to be trusted in cloud service providers, add them here - CSRF_TRUSTED_ORIGINS += [] - # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (get_secret('BACKEND_DEBUG') == 'True') @@ -142,17 +125,18 @@ MIDDLEWARE = [ # https://docs.djangoproject.com/en/4.2/howto/static-files/ ROOT_URLCONF = 'config.urls' -if CLOUD: +if SERVE_MEDIA: # Cloud Storage Settings + # This is assuming you use the same bucket for media and static containers CLOUD_BUCKET = get_secret('CLOUD_BUCKET') - CLOUD_BUCKET_CONTAINER = get_secret('CLOUD_BUCKET_CONTAINER') - CLOUD_STATIC_CONTAINER = get_secret('CLOUD_STATIC_CONTAINER') + MEDIA_CONTAINER = get_secret('MEDIA_CONTAINER') + STATIC_CONTAINER = get_secret('STATIC_CONTAINER') - MEDIA_URL = f'https://{CLOUD_BUCKET}/{CLOUD_BUCKET_CONTAINER}/' + MEDIA_URL = f'https://{CLOUD_BUCKET}/{MEDIA_CONTAINER}/' MEDIA_ROOT = f'https://{CLOUD_BUCKET}/' - STATIC_URL = f'https://{CLOUD_BUCKET}/{CLOUD_STATIC_CONTAINER}/' - STATIC_ROOT = f'https://{CLOUD_BUCKET}/{CLOUD_STATIC_CONTAINER}/' + STATIC_URL = f'https://{CLOUD_BUCKET}/{STATIC_CONTAINER}/' + STATIC_ROOT = f'https://{CLOUD_BUCKET}/{STATIC_CONTAINER}/' # Consult django-storages documentation when filling in these values. This will vary depending on your cloud service provider STORAGES = { @@ -235,7 +219,7 @@ WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", - # Have this set to True if you're using a connection bouncer + # Set to True to avoid issues with pgbouncer when pooling connections 'DISABLE_SERVER_SIDE_CURSORS': True, "NAME": get_secret("DB_DATABASE"), "USER": get_secret("DB_USERNAME"), @@ -247,6 +231,16 @@ DATABASES = { }, } } +# Django Cache +CACHES = { + "default": { + "BACKEND": "django_redis.cache.RedisCache", + "LOCATION": f"redis://{get_secret('REDIS_HOST')}:{get_secret('REDIS_PORT')}/2", + "OPTIONS": { + "CLIENT_CLASS": "django_redis.client.DefaultClient", + } + } +} AUTH_USER_MODEL = 'accounts.CustomUser' @@ -314,7 +308,7 @@ AUTH_PASSWORD_VALIDATORS = [ LANGUAGE_CODE = 'en-us' -TIME_ZONE = 'Asia/Manila' +TIME_ZONE = get_secret('TIMEZONE') USE_I18N = True @@ -330,7 +324,7 @@ SITE_NAME = 'DRF-Template' # JWT Token Lifetimes SIMPLE_JWT = { - "ACCESS_TOKEN_LIFETIME": timedelta(hours=6), + "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=3) } @@ -373,14 +367,3 @@ DATA_UPLOAD_MAX_NUMBER_FIELDS = 20480 GRAPH_MODELS = { 'app_labels': ['accounts', 'user_groups', 'billing', 'emails', 'payments', 'subscriptions'] } - -# Django/DRF Cache -CACHES = { - "default": { - "BACKEND": "django_redis.cache.RedisCache", - "LOCATION": f"redis://{get_secret('REDIS_HOST')}:{get_secret('REDIS_PORT')}/2", - "OPTIONS": { - "CLIENT_CLASS": "django_redis.client.DefaultClient", - } - } -} diff --git a/backend/payments/views.py b/backend/payments/views.py index 123ee21..c4583b1 100644 --- a/backend/payments/views.py +++ b/backend/payments/views.py @@ -1,4 +1,4 @@ -from config.settings import STRIPE_SECRET_KEY, DOMAIN, STRIPE_SECRET_WEBHOOK, CLOUD, BACKEND_URL, FRONTEND_URL +from config.settings import STRIPE_SECRET_KEY, STRIPE_SECRET_WEBHOOK, FRONTEND_URL from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response