Files
mostovik-backend/src/config/settings/base.py
Aleksandr Meshchriakov cbfbd8652d feat: Add comprehensive Django user app with tests using model-bakery
- Implemented user authentication with JWT tokens
- Added user and profile models with OneToOne relationship
- Created service layer for business logic separation
- Implemented DRF serializers and views
- Added comprehensive test suite with model-bakery factories
- Fixed ipdb/pdbpp dependency conflicts with custom test runner
- Configured development and production environments
- Added deployment configurations for Apache, systemd, and Docker
2026-01-19 14:12:33 +01:00

242 lines
6.7 KiB
Python

"""
Base settings for Django project.
Generated by 'django-admin startproject' using Django 3.2.25.
"""
import os
from pathlib import Path
from decouple import Config, RepositoryEnv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Load environment variables
ENV_FILE = BASE_DIR / ".env"
if ENV_FILE.exists():
config = Config(RepositoryEnv(str(ENV_FILE)))
else:
from decouple import AutoConfig
config = AutoConfig(search_path=BASE_DIR)
# Helper function for getting config values
def get_env(key, default=None):
return config(key, default=default)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env("SECRET_KEY", "django-insecure-development-key-change-in-production")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_env("DEBUG", True)
if isinstance(DEBUG, str):
DEBUG = DEBUG.lower() in ('true', '1', 'yes')
ALLOWED_HOSTS = get_env("ALLOWED_HOSTS", "localhost,127.0.0.1")
if isinstance(ALLOWED_HOSTS, str):
ALLOWED_HOSTS = ALLOWED_HOSTS.split(",")
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# Third-party apps
"rest_framework",
"corsheaders",
"django_celery_beat",
"django_celery_results",
"drf_yasg",
# Local apps
"apps.user",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"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 = "config.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"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"
# Database
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": get_env("POSTGRES_DB", "project_db"),
"USER": get_env("POSTGRES_USER", "project_user"),
"PASSWORD": get_env("POSTGRES_PASSWORD", "project_password"),
"HOST": get_env("POSTGRES_HOST", "db"),
"PORT": int(get_env("POSTGRES_PORT", "5432")),
"OPTIONS": {
"charset": "utf8mb4",
},
},
}
# Password validation
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
LANGUAGE_CODE = "ru-RU"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static"]
# Media files
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
# Default primary key field type
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Custom user model
AUTH_USER_MODEL = "user.User"
# REST Framework settings
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_simplejwt.authentication.JWTAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
"DEFAULT_RENDERER_CLASSES": [
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer",
],
}
# JWT settings
from datetime import timedelta
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
"UPDATE_LAST_LOGIN": True,
"ALGORITHM": "HS256",
"SIGNING_KEY": SECRET_KEY,
"VERIFYING_KEY": None,
"AUDIENCE": None,
"ISSUER": None,
"JWK_URL": None,
"LEEWAY": 0,
"AUTH_HEADER_TYPES": ("Bearer",),
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
"TOKEN_TYPE_CLAIM": "token_type",
"TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",
"JTI_CLAIM": "jti",
"SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
"SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
"SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}
# CORS settings
CORS_ALLOWED_ORIGINS = get_env("CORS_ALLOWED_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000")
if isinstance(CORS_ALLOWED_ORIGINS, str):
CORS_ALLOWED_ORIGINS = CORS_ALLOWED_ORIGINS.split(",")
CORS_ALLOW_CREDENTIALS = True
# Logging configuration
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}",
"style": "{",
},
"simple": {
"format": "{levelname} {message}",
"style": "{",
},
},
"handlers": {
"file": {
"level": "INFO",
"class": "logging.FileHandler",
"filename": BASE_DIR / "logs/django.log",
"formatter": "verbose",
},
"console": {
"level": "INFO",
"class": "logging.StreamHandler",
"formatter": "simple",
},
},
"root": {
"handlers": ["console", "file"],
"level": "INFO",
},
"loggers": {
"django": {
"handlers": ["console", "file"],
"level": "INFO",
"propagate": False,
},
},
}