gapguide-api / config /settings.py
arifRB's picture
Deploy GapGuide backend (Docker)
ffd36e0 verified
Raw
History Blame Contribute Delete
9.38 kB
import os
from pathlib import Path
from datetime import timedelta
from dotenv import load_dotenv
from django.core.exceptions import ImproperlyConfigured
load_dotenv()
BASE_DIR = Path(__file__).resolve().parent.parent
_INSECURE_DEFAULT_SECRET = 'django-insecure-change-me'
SECRET_KEY = os.getenv('SECRET_KEY', _INSECURE_DEFAULT_SECRET)
DEBUG = os.getenv('DEBUG', 'False').lower() in ('true', '1', 'yes')
if not DEBUG and SECRET_KEY == _INSECURE_DEFAULT_SECRET:
raise ImproperlyConfigured(
"SECRET_KEY must be set via environment when DEBUG is False. "
"Set a strong random value in the SECRET_KEY env var."
)
ALLOWED_HOSTS = [h.strip() for h in os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') if h.strip()]
# Deployment (HF Spaces + Neon): a single DATABASE_URL takes precedence when
# set. Locally it is unset, so the explicit DB_* settings below are used
# unchanged. dj_database_url is imported lazily so local dev needn't install it.
if os.getenv('DATABASE_URL'):
import dj_database_url
DATABASES = {
'default': dj_database_url.parse(
os.getenv('DATABASE_URL'), conn_max_age=0, ssl_require=True,
)
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DB_NAME', 'gapguide_db'),
'USER': os.getenv('DB_USER', 'postgres'),
'PASSWORD': os.getenv('DB_PASSWORD', 'postgres'),
'HOST': os.getenv('DB_HOST', 'localhost'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
'rest_framework',
'rest_framework_simplejwt',
'rest_framework_simplejwt.token_blacklist',
'corsheaders',
'drf_spectacular',
'django_filters',
'apps.accounts',
'apps.skills',
'apps.roles',
'apps.analysis',
'apps.resources',
'apps.progress',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# WhiteNoise serves static files (Django admin / DRF) in the container with
# no nginx. Must sit immediately after SecurityMiddleware. No-op locally
# under runserver (DEBUG=True serves static via staticfiles finders).
'whitenoise.middleware.WhiteNoiseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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 = 'config.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 = 'config.wsgi.application'
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'},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
# collectstatic target (used in the container build). Non-manifest WhiteNoise
# storage β†’ no collectstatic required for local `runserver`.
STATIC_ROOT = BASE_DIR / 'staticfiles'
STORAGES = {
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {"BACKEND": "whitenoise.storage.CompressedStaticFilesStorage"},
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'accounts.User'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.ScopedRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'login': '10/minute',
'register': '20/hour',
# F28 β€” the resume-parse endpoint runs the full NER chain (expensive).
# ScopedRateThrottle is a no-op until BOTH this rate key and the view's
# throttle_scope='resume_parse' exist; a missing/typo'd key here raises
# ImproperlyConfigured (500) on every parse, so keep them in lockstep.
'resume_parse': os.getenv('THROTTLE_RESUME', '30/hour'),
},
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': True,
'ALGORITHM': 'HS256',
'AUTH_HEADER_TYPES': ('Bearer',),
}
CORS_ALLOWED_ORIGINS = [o.strip() for o in os.getenv('CORS_ALLOWED_ORIGINS', 'http://localhost:5173').split(',') if o.strip()]
# F27 β€” production hardening. Applied only when DEBUG is off (dev runs plain
# http on localhost). `python manage.py check --deploy` (with a prod-like env:
# DEBUG=False + a real SECRET_KEY + ALLOWED_HOSTS) verifies these resolve the
# W004/W008/W012/W016 warnings. SECURE_PROXY_SSL_HEADER requires the upstream
# proxy to set X-Forwarded-Proto (else SECURE_SSL_REDIRECT can loop).
if not DEBUG:
# Env-toggle: behind HF Spaces' HTTPS edge we start this False to avoid a
# redirect loop if the proxy doesn't forward X-Forwarded-Proto. SECURE_PROXY_
# SSL_HEADER stays always-on (harmless if absent, correct if present) so
# request.is_secure() β€” and thus secure cookies / admin login β€” works.
SECURE_SSL_REDIRECT = os.getenv('SECURE_SSL_REDIRECT', 'True').lower() in ('true', '1', 'yes')
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = [
o.strip() for o in os.getenv('CSRF_TRUSTED_ORIGINS', '').split(',')
if o.strip()
]
# Resume parser caps at 5 MB (see apps.accounts.resume_parser.MAX_PDF_BYTES).
# Raise Django's defaults (both are 2.5 MB) so 3–5 MB PDFs stay in memory
# instead of silently spooling to /tmp during parse.
FILE_UPLOAD_MAX_MEMORY_SIZE = 6 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = 6 * 1024 * 1024
SPECTACULAR_SETTINGS = {
'TITLE': 'GapGuide API',
'DESCRIPTION': 'API documentation for GapGuide - Skill Gap Analysis Platform',
'VERSION': '1.0.0',
# Four fields expose the same (BEGINNER, INTERMEDIATE, ADVANCED) choice set:
# Skill.difficulty_level, UserSkill.user_level, RoleSkill.required_level, and
# Resource.difficulty_level. Without explicit overrides drf-spectacular emits
# a "multiple names for same choice set" warning on schema build.
'ENUM_NAME_OVERRIDES': {
'DifficultyLevelEnum': 'apps.skills.models.Skill.DIFFICULTY_CHOICES',
},
}
# F30 β€” logging. Console always + a rotating file. The NER layers log under
# apps.accounts.* so handlers attach to the 'apps' logger (a django-only config
# would miss them). RotatingFileHandler opens its file at construction, so the
# log dir must exist first (module-level mkdir guard).
_LOG_DIR = BASE_DIR / 'logs'
try:
_LOG_DIR.mkdir(parents=True, exist_ok=True)
except OSError:
# Read-only / restricted FS: don't crash settings import. The file handler
# opens lazily (delay=True); the console handler is always available.
pass
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {'format': '{asctime} {levelname} {name}: {message}', 'style': '{'},
},
'handlers': {
'console': {'class': 'logging.StreamHandler', 'formatter': 'verbose'},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': str(_LOG_DIR / 'gapguide.log'),
'maxBytes': 5 * 1024 * 1024,
'backupCount': 3,
'formatter': 'verbose',
'delay': True, # open the file on first emit, not at import time
},
},
'root': {'handlers': ['console', 'file'], 'level': 'INFO'},
'loggers': {
'apps': {'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': False},
'django': {'handlers': ['console', 'file'], 'level': 'WARNING', 'propagate': False},
},
}