mirror of
https://github.com/lemeow125/DRF_Template.git
synced 2025-04-28 10:41:15 +08:00
Overhauled entire project config, added notifications, email templates, optimized stripe subscriptions, redis caching, and webdriver utilities
This commit is contained in:
parent
7cbe8fd720
commit
99dfcef67b
84 changed files with 4300 additions and 867 deletions
|
@ -0,0 +1,3 @@
|
|||
from .celery import app as celery_app
|
||||
|
||||
__all__ = ('celery_app',)
|
17
backend/config/celery.py
Normal file
17
backend/config/celery.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
from celery import Celery
|
||||
import os
|
||||
|
||||
|
||||
# Set the default Django settings module for the 'celery' program.
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
||||
|
||||
app = Celery('config')
|
||||
|
||||
# Using a string here means the worker doesn't have to serialize
|
||||
# the configuration object to child processes.
|
||||
# - namespace='CELERY' means all celery-related configuration keys
|
||||
# should have a `CELERY_` prefix.
|
||||
app.config_from_object('django.conf:settings', namespace='CELERY')
|
||||
|
||||
# Load task modules from all registered Django apps.
|
||||
app.autodiscover_tasks()
|
|
@ -12,50 +12,91 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
|
|||
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv # Python dotenv
|
||||
from dotenv import load_dotenv, find_dotenv # Python dotenv
|
||||
import os
|
||||
|
||||
load_dotenv() # loads the configs from .env
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
# Backend folder (/backend)
|
||||
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))
|
||||
|
||||
load_dotenv(find_dotenv())
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
|
||||
def get_secret(secret_name):
|
||||
if CLOUD:
|
||||
try:
|
||||
pass
|
||||
# Add specific implementations here if deploying to Azure, GCP, or AWS to get secrets
|
||||
except:
|
||||
secret_value = ""
|
||||
else:
|
||||
# Fallback to .env or system environment variables for local development
|
||||
secret_value = os.getenv(secret_name)
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = str(os.getenv('SECRET_KEY'))
|
||||
if secret_value is None:
|
||||
raise ValueError(f"Secret '{secret_name}' not found.")
|
||||
else:
|
||||
return secret_value
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
# 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}'
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
CSRF_TRUSTED_ORIGINS = ["https://testing.keannu1.duckdns.org"]
|
||||
CSRF_TRUSTED_ORIGINS = [
|
||||
BACKEND_URL,
|
||||
FRONTEND_URL
|
||||
]
|
||||
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')
|
||||
# Determines whether or not to insert test data within tables
|
||||
SEED_DATA = (get_secret('SEED_DATA') == 'True')
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = get_secret('SECRET_KEY')
|
||||
# Selenium Config
|
||||
# Initiate CAPTCHA solver in test mode
|
||||
CAPTCHA_TESTING = (get_secret('CAPTCHA_TESTING') == 'True')
|
||||
# If using Selenium and/or the provided CAPTCHA solver, determines whether or not to use proxies
|
||||
USE_PROXY = (get_secret('USE_PROXY') == 'True')
|
||||
|
||||
# Stripe (For payments)
|
||||
STRIPE_SECRET_KEY = get_secret(
|
||||
"STRIPE_SECRET_KEY")
|
||||
STRIPE_SECRET_WEBHOOK = get_secret('STRIPE_SECRET_WEBHOOK')
|
||||
STRIPE_CHECKOUT_URL = f''
|
||||
|
||||
# Email credentials
|
||||
EMAIL_HOST = ''
|
||||
EMAIL_HOST_USER = ''
|
||||
EMAIL_HOST_PASSWORD = ''
|
||||
EMAIL_PORT = ''
|
||||
EMAIL_USE_TLS = False
|
||||
|
||||
if (DEBUG == True):
|
||||
EMAIL_HOST = str(os.getenv('DEV_EMAIL_HOST'))
|
||||
EMAIL_HOST_USER = str(os.getenv('DEV_EMAIL_HOST_USER'))
|
||||
EMAIL_HOST_PASSWORD = str(os.getenv('DEV_EMAIL_HOST_PASSWORD'))
|
||||
EMAIL_PORT = str(os.getenv('DEV_EMAIL_PORT'))
|
||||
else:
|
||||
EMAIL_HOST = str(os.getenv('PROD_EMAIL_HOST'))
|
||||
EMAIL_HOST_USER = str(os.getenv('PROD_EMAIL_HOST_USER'))
|
||||
EMAIL_HOST_PASSWORD = str(os.getenv('PROD_EMAIL_HOST_PASSWORD'))
|
||||
EMAIL_PORT = str(os.getenv('PROD_EMAIL_PORT'))
|
||||
EMAIL_USE_TLS = str(os.getenv('PROD_EMAIL_TLS'))
|
||||
EMAIL_HOST = get_secret('EMAIL_HOST')
|
||||
EMAIL_HOST_USER = get_secret('EMAIL_HOST_USER')
|
||||
EMAIL_HOST_PASSWORD = get_secret('EMAIL_HOST_PASSWORD')
|
||||
EMAIL_PORT = get_secret('EMAIL_PORT')
|
||||
EMAIL_USE_TLS = get_secret('EMAIL_USE_TLS')
|
||||
EMAIL_ADDRESS = (get_secret('EMAIL_ADDRESS') == 'True')
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'silk',
|
||||
'config',
|
||||
'unfold',
|
||||
'unfold.contrib.filters',
|
||||
'unfold.contrib.simple_history',
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
|
@ -63,20 +104,32 @@ INSTALLED_APPS = [
|
|||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'storages',
|
||||
'django_extensions',
|
||||
'rest_framework',
|
||||
'rest_framework_simplejwt',
|
||||
'django_celery_results',
|
||||
'django_celery_beat',
|
||||
'simple_history',
|
||||
'djoser',
|
||||
'corsheaders',
|
||||
'drf_spectacular',
|
||||
'drf_spectacular_sidecar',
|
||||
'webdriver',
|
||||
'accounts',
|
||||
'user_groups',
|
||||
'subscriptions',
|
||||
'payments',
|
||||
'billing',
|
||||
'emails',
|
||||
'notifications'
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
"silk.middleware.SilkyMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"corsheaders.middleware.CorsMiddleware",
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
|
@ -88,17 +141,50 @@ MIDDLEWARE = [
|
|||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/4.2/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
||||
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
|
||||
MEDIA_URL = 'api/v1/media/'
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
|
||||
ROOT_URLCONF = 'config.urls'
|
||||
if CLOUD:
|
||||
# Cloud Storage Settings
|
||||
CLOUD_BUCKET = get_secret('CLOUD_BUCKET')
|
||||
CLOUD_BUCKET_CONTAINER = get_secret('CLOUD_BUCKET_CONTAINER')
|
||||
CLOUD_STATIC_CONTAINER = get_secret('CLOUD_STATIC_CONTAINER')
|
||||
|
||||
MEDIA_URL = f'https://{CLOUD_BUCKET}/{CLOUD_BUCKET_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}/'
|
||||
|
||||
# Consult django-storages documentation when filling in these values. This will vary depending on your cloud service provider
|
||||
STORAGES = {
|
||||
'default': {
|
||||
# TODO: Set this up here if you're using cloud storage
|
||||
'BACKEND': None,
|
||||
'OPTIONS': {
|
||||
# Optional parameters
|
||||
},
|
||||
},
|
||||
'staticfiles': {
|
||||
# TODO: Set this up here if you're using cloud storage
|
||||
'BACKEND': None,
|
||||
'OPTIONS': {
|
||||
# Optional parameters
|
||||
},
|
||||
},
|
||||
}
|
||||
else:
|
||||
STATIC_URL = 'static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
||||
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
|
||||
MEDIA_URL = 'api/v1/media/'
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
|
||||
ROOT_URLCONF = 'config.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'DIRS': [
|
||||
BASE_DIR / 'templates',
|
||||
],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
|
@ -135,26 +221,30 @@ REST_FRAMEWORK = {
|
|||
|
||||
# DRF-Spectacular
|
||||
SPECTACULAR_SETTINGS = {
|
||||
'TITLE': 'Test Backend',
|
||||
'DESCRIPTION': 'A Project by Keannu Bernasol',
|
||||
'TITLE': 'DRF-Template',
|
||||
'DESCRIPTION': 'A Template Project by Keannu Bernasol',
|
||||
'VERSION': '1.0.0',
|
||||
'SERVE_INCLUDE_SCHEMA': False,
|
||||
'SWAGGER_UI_DIST': 'SIDECAR',
|
||||
'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
|
||||
'REDOC_DIST': 'SIDECAR',
|
||||
# OTHER SETTINGS
|
||||
}
|
||||
|
||||
WSGI_APPLICATION = 'config.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',
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
# Have this set to True if you're using a connection bouncer
|
||||
'DISABLE_SERVER_SIDE_CURSORS': True,
|
||||
"NAME": get_secret("DB_DATABASE"),
|
||||
"USER": get_secret("DB_USERNAME"),
|
||||
"PASSWORD": get_secret("DB_PASSWORD"),
|
||||
"HOST": get_secret("DB_HOST"),
|
||||
"PORT": get_secret("DB_PORT"),
|
||||
"OPTIONS": {
|
||||
"sslmode": get_secret("DB_SSL_MODE")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -166,11 +256,22 @@ DJOSER = {
|
|||
'PASSWORD_RESET_CONFIRM_URL': 'reset_password_confirm/{uid}/{token}',
|
||||
'ACTIVATION_URL': 'activation/{uid}/{token}',
|
||||
'USER_AUTHENTICATION_RULES': ['djoser.authentication.TokenAuthenticationRule'],
|
||||
'EMAIL': {
|
||||
'activation': 'emails.templates.ActivationEmail',
|
||||
'password_reset': 'emails.templates.PasswordResetEmail'
|
||||
},
|
||||
'SERIALIZERS': {
|
||||
'user': 'accounts.serializers.CustomUserSerializer',
|
||||
'current_user': 'accounts.serializers.CustomUserSerializer',
|
||||
'user_create': 'accounts.serializers.UserRegistrationSerializer',
|
||||
},
|
||||
'PERMISSIONS': {
|
||||
# Disable some unneeded endpoints by setting them to admin only
|
||||
'username_reset': ['rest_framework.permissions.IsAdminUser'],
|
||||
'username_reset_confirm': ['rest_framework.permissions.IsAdminUser'],
|
||||
'set_username': ['rest_framework.permissions.IsAdminUser'],
|
||||
'set_password': ['rest_framework.permissions.IsAdminUser'],
|
||||
}
|
||||
}
|
||||
|
||||
# Password validation
|
||||
|
@ -182,6 +283,9 @@ AUTH_PASSWORD_VALIDATORS = [
|
|||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
"OPTIONS": {
|
||||
"min_length": 8,
|
||||
}
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
|
@ -189,6 +293,19 @@ AUTH_PASSWORD_VALIDATORS = [
|
|||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
# Additional password validators
|
||||
{
|
||||
'NAME': 'accounts.validators.SpecialCharacterValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'accounts.validators.LowercaseValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'accounts.validators.UppercaseValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'accounts.validators.NumberValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
|
@ -209,18 +326,61 @@ USE_TZ = True
|
|||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
|
||||
DOMAIN = 'testing.keannu1.duckdns.org/#'
|
||||
SITE_NAME = 'DRF-Template'
|
||||
|
||||
SITE_NAME = 'Test Backend'
|
||||
|
||||
# 1 week access token lifetime
|
||||
# JWT Token Lifetimes
|
||||
SIMPLE_JWT = {
|
||||
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=10080),
|
||||
"REFRESH_TOKEN_LIFETIME": timedelta(minutes=10080)
|
||||
"ACCESS_TOKEN_LIFETIME": timedelta(hours=6),
|
||||
"REFRESH_TOKEN_LIFETIME": timedelta(days=3)
|
||||
}
|
||||
|
||||
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
|
||||
SESSION_CACHE_ALIAS = "default"
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True
|
||||
CORS_ALLOW_CREDENTIALS = True
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
},
|
||||
},
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "DEBUG",
|
||||
},
|
||||
}
|
||||
DJANGO_LOG_LEVEL = "DEBUG"
|
||||
# Enables VS Code debugger to break on raised exceptions
|
||||
DEBUG_PROPAGATE_EXCEPTIONS = "DEBUG"
|
||||
|
||||
# Celery Configuration Options
|
||||
CELERY_TIMEZONE = TIME_ZONE
|
||||
CELERY_TASK_TRACK_STARTED = True
|
||||
CELERY_TASK_TIME_LIMIT = 30 * 60
|
||||
CELERY_BROKER_URL = get_secret("CELERY_BROKER")
|
||||
CELERY_BROKER = get_secret("CELERY_BROKER")
|
||||
CELERY_BACKEND = get_secret("CELERY_BROKER")
|
||||
CELERY_RESULT_BACKEND = get_secret("CELERY_RESULT_BACKEND")
|
||||
CELERY_RESULT_EXTENDED = True
|
||||
|
||||
# Celery Beat Options
|
||||
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
|
||||
|
||||
# Maximum number of rows that can be updated within the Django admin panel
|
||||
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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@ Including another URLconf
|
|||
from django.contrib import admin
|
||||
from django.urls import path, include
|
||||
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
|
||||
from config.settings import DEBUG
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
|
@ -27,3 +28,6 @@ urlpatterns = [
|
|||
path('redoc/',
|
||||
SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
|
||||
]
|
||||
|
||||
if DEBUG:
|
||||
urlpatterns += [path('silk/', include('silk.urls', namespace='silk'))]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue