Backend (Django 4.2 + DRF): - accounts: phone OTP login, JWT, profile, addresses - catalog: categories, products, images, filters, search, hits/new/related - orders: creation with Idempotency-Key, stock reservation, status history, cancel - loyalty: bonus accounts, promo codes, gift certificates - payments: payment records and YooKassa webhook handling - content: static pages, banners, site settings - integration: 1C exchange (catalog sync, order push via outbox, statuses, bonuses) - common: error envelope, pagination, request-id, integration auth, admin dashboard Infrastructure: Dockerfile, docker-compose (Postgres, Redis, Celery worker/beat, Nginx), requirements split by environment, OpenAPI contracts for site and 1C, architecture doc. Tests: 22 pytest cases covering catalog, orders, idempotency, OTP, integration.
293 lines
9.9 KiB
Python
293 lines
9.9 KiB
Python
"""Django settings shared by all environments."""
|
|
from datetime import timedelta
|
|
from pathlib import Path
|
|
import os
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
|
# Support both the repository root .env (Docker Compose) and backend/.env (local).
|
|
load_dotenv(BASE_DIR.parent / ".env")
|
|
load_dotenv(BASE_DIR / ".env", override=True)
|
|
|
|
|
|
def env(name: str, default: str | None = None) -> str | None:
|
|
return os.environ.get(name, default)
|
|
|
|
|
|
def env_bool(name: str, default: bool = False) -> bool:
|
|
return str(env(name, str(default))).strip().lower() in {"1", "true", "yes", "on"}
|
|
|
|
|
|
def env_int(name: str, default: int) -> int:
|
|
try:
|
|
return int(env(name, str(default)) or default)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def env_list(name: str, default: str = "") -> list[str]:
|
|
raw = env(name, default) or ""
|
|
return [item.strip() for item in raw.split(",") if item.strip()]
|
|
|
|
|
|
# --- Core -------------------------------------------------------------------
|
|
SECRET_KEY = env("DJANGO_SECRET_KEY", "dev-insecure-change-me")
|
|
DEBUG = env_bool("DJANGO_DEBUG", False)
|
|
ALLOWED_HOSTS = env_list("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1")
|
|
|
|
# --- Applications -----------------------------------------------------------
|
|
INSTALLED_APPS = [
|
|
"django.contrib.admin",
|
|
"django.contrib.auth",
|
|
"django.contrib.contenttypes",
|
|
"django.contrib.sessions",
|
|
"django.contrib.messages",
|
|
"django.contrib.staticfiles",
|
|
# Third-party
|
|
"rest_framework",
|
|
"rest_framework_simplejwt",
|
|
"drf_spectacular",
|
|
"django_filters",
|
|
"corsheaders",
|
|
# Local
|
|
"apps.common",
|
|
"apps.accounts",
|
|
"apps.catalog",
|
|
"apps.orders",
|
|
"apps.payments",
|
|
"apps.loyalty",
|
|
"apps.integration",
|
|
"apps.content",
|
|
]
|
|
|
|
MIDDLEWARE = [
|
|
"django.middleware.security.SecurityMiddleware",
|
|
"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",
|
|
"apps.common.middleware.RequestIDMiddleware",
|
|
]
|
|
|
|
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"
|
|
ASGI_APPLICATION = "config.asgi.application"
|
|
|
|
# --- Database ---------------------------------------------------------------
|
|
if env("DB_ENGINE", "sqlite") == "postgres":
|
|
DATABASES = {
|
|
"default": {
|
|
"ENGINE": "django.db.backends.postgresql",
|
|
"NAME": env("POSTGRES_DB", "homm"),
|
|
"USER": env("POSTGRES_USER", "homm"),
|
|
"PASSWORD": env("POSTGRES_PASSWORD", "homm"),
|
|
"HOST": env("POSTGRES_HOST", "localhost"),
|
|
"PORT": env("POSTGRES_PORT", "5432"),
|
|
"CONN_MAX_AGE": 60,
|
|
}
|
|
}
|
|
else:
|
|
DATABASES = {
|
|
"default": {
|
|
"ENGINE": "django.db.backends.sqlite3",
|
|
"NAME": BASE_DIR / "db.sqlite3",
|
|
}
|
|
}
|
|
|
|
# --- Cache / Celery ---------------------------------------------------------
|
|
REDIS_URL = env("REDIS_URL", "")
|
|
if REDIS_URL:
|
|
CACHES = {
|
|
"default": {
|
|
"BACKEND": "django.core.cache.backends.redis.RedisCache",
|
|
"LOCATION": REDIS_URL,
|
|
}
|
|
}
|
|
else:
|
|
CACHES = {
|
|
"default": {
|
|
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
|
|
"LOCATION": "homm-local",
|
|
}
|
|
}
|
|
|
|
CELERY_BROKER_URL = env("CELERY_BROKER_URL", REDIS_URL or "redis://localhost:6379/0")
|
|
CELERY_RESULT_BACKEND = env("CELERY_RESULT_BACKEND", CELERY_BROKER_URL)
|
|
CELERY_TASK_SERIALIZER = "json"
|
|
CELERY_RESULT_SERIALIZER = "json"
|
|
CELERY_ACCEPT_CONTENT = ["json"]
|
|
CELERY_TIMEZONE = "Europe/Moscow"
|
|
CELERY_TASK_TRACK_STARTED = True
|
|
CELERY_TASK_TIME_LIMIT = 30 * 60
|
|
CELERY_BEAT_SCHEDULE = {
|
|
"sync-catalog-from-1c": {
|
|
"task": "apps.integration.tasks.sync_catalog_from_1c",
|
|
"schedule": 600.0, # every 10 minutes
|
|
},
|
|
"process-outbox": {
|
|
"task": "apps.integration.tasks.process_outbox",
|
|
"schedule": 60.0,
|
|
},
|
|
"pull-order-statuses": {
|
|
"task": "apps.integration.tasks.pull_order_statuses",
|
|
"schedule": 300.0,
|
|
},
|
|
}
|
|
|
|
# --- Auth -------------------------------------------------------------------
|
|
AUTH_USER_MODEL = "accounts.User"
|
|
|
|
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"},
|
|
]
|
|
|
|
SIMPLE_JWT = {
|
|
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=30),
|
|
"REFRESH_TOKEN_LIFETIME": timedelta(days=30),
|
|
"ROTATE_REFRESH_TOKENS": True,
|
|
"BLACKLIST_AFTER_ROTATION": False,
|
|
"AUTH_HEADER_TYPES": ("Bearer",),
|
|
}
|
|
|
|
# --- DRF --------------------------------------------------------------------
|
|
REST_FRAMEWORK = {
|
|
"DEFAULT_AUTHENTICATION_CLASSES": (
|
|
"rest_framework_simplejwt.authentication.JWTAuthentication",
|
|
),
|
|
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
|
|
"DEFAULT_PAGINATION_CLASS": "apps.common.pagination.DefaultPagination",
|
|
"PAGE_SIZE": 24,
|
|
"DEFAULT_FILTER_BACKENDS": (
|
|
"django_filters.rest_framework.DjangoFilterBackend",
|
|
"rest_framework.filters.SearchFilter",
|
|
"rest_framework.filters.OrderingFilter",
|
|
),
|
|
"EXCEPTION_HANDLER": "apps.common.exceptions.api_exception_handler",
|
|
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
|
|
"DEFAULT_THROTTLE_CLASSES": (
|
|
"rest_framework.throttling.AnonRateThrottle",
|
|
"rest_framework.throttling.UserRateThrottle",
|
|
),
|
|
"DEFAULT_THROTTLE_RATES": {
|
|
"anon": "120/min",
|
|
"user": "240/min",
|
|
"otp": "5/min",
|
|
},
|
|
}
|
|
|
|
SPECTACULAR_SETTINGS = {
|
|
"TITLE": "HOMM Store API",
|
|
"DESCRIPTION": (
|
|
"Public storefront API and the integration API used by 1C. "
|
|
"See docs/architecture.md for the exchange design."
|
|
),
|
|
"VERSION": "1.0.0",
|
|
"SERVE_INCLUDE_SCHEMA": False,
|
|
"COMPONENT_SPLIT_REQUEST": True,
|
|
"SORT_OPERATIONS": False,
|
|
"ENUM_NAME_OVERRIDES": {
|
|
"OrderStatusEnum": "apps.orders.models.Order.Status",
|
|
"OrderPaymentStatusEnum": "apps.orders.models.Order.PaymentStatus",
|
|
"PaymentMethodEnum": "apps.payments.models.Payment.Method",
|
|
"PaymentStatusEnum": "apps.payments.models.Payment.Status",
|
|
"ProductStockStatusEnum": "apps.catalog.models.Product.StockStatus",
|
|
"BonusReasonEnum": "apps.loyalty.models.BonusTransaction.Reason",
|
|
"CertificateStatusEnum": "apps.loyalty.models.GiftCertificate.Status",
|
|
"PromoDiscountTypeEnum": "apps.loyalty.models.PromoCode.DiscountType",
|
|
"SyncDirectionEnum": "apps.integration.models.SyncRun.Direction",
|
|
"SyncEntityEnum": "apps.integration.models.SyncRun.Entity",
|
|
"SyncRunStatusEnum": "apps.integration.models.SyncRun.Status",
|
|
"OutboxStatusEnum": "apps.integration.models.OutboxMessage.Status",
|
|
},
|
|
}
|
|
|
|
# --- CORS -------------------------------------------------------------------
|
|
CORS_ALLOWED_ORIGINS = env_list(
|
|
"CORS_ALLOWED_ORIGINS", "http://localhost:3000,http://localhost:5173"
|
|
)
|
|
CORS_ALLOW_CREDENTIALS = True
|
|
|
|
# --- Internationalization ---------------------------------------------------
|
|
LANGUAGE_CODE = "ru-ru"
|
|
TIME_ZONE = "Europe/Moscow"
|
|
USE_I18N = True
|
|
USE_TZ = True
|
|
|
|
# --- Static / media ---------------------------------------------------------
|
|
STATIC_URL = "static/"
|
|
STATIC_ROOT = BASE_DIR / "staticfiles"
|
|
MEDIA_URL = "media/"
|
|
MEDIA_ROOT = BASE_DIR / "media"
|
|
|
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
|
|
|
# --- Email ------------------------------------------------------------------
|
|
EMAIL_BACKEND = env(
|
|
"EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend"
|
|
)
|
|
DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL", "noreply@homm.local")
|
|
|
|
# --- OTP --------------------------------------------------------------------
|
|
OTP_TTL_SECONDS = env_int("OTP_TTL_SECONDS", 300)
|
|
OTP_MAX_ATTEMPTS = env_int("OTP_MAX_ATTEMPTS", 5)
|
|
OTP_DEBUG_CODE = env("OTP_DEBUG_CODE", "")
|
|
# Never enable in production: exposes the OTP code in the API response.
|
|
OTP_EXPOSE_DEBUG_CODE = env_bool("OTP_EXPOSE_DEBUG_CODE", False)
|
|
|
|
# --- 1C integration ---------------------------------------------------------
|
|
INTEGRATION_API_TOKEN = env("INTEGRATION_API_TOKEN", "dev-integration-token")
|
|
ONEC_BASE_URL = env("ONEC_BASE_URL", "")
|
|
ONEC_USERNAME = env("ONEC_USERNAME", "")
|
|
ONEC_PASSWORD = env("ONEC_PASSWORD", "")
|
|
ONEC_TIMEOUT = env_int("ONEC_TIMEOUT", 30)
|
|
|
|
# --- Payments ---------------------------------------------------------------
|
|
YOOKASSA_SHOP_ID = env("YOOKASSA_SHOP_ID", "")
|
|
YOOKASSA_SECRET_KEY = env("YOOKASSA_SECRET_KEY", "")
|
|
YOOKASSA_RETURN_URL = env("YOOKASSA_RETURN_URL", "")
|
|
|
|
# --- Logging ----------------------------------------------------------------
|
|
LOGGING = {
|
|
"version": 1,
|
|
"disable_existing_loggers": False,
|
|
"formatters": {
|
|
"verbose": {
|
|
"format": "%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
},
|
|
},
|
|
"handlers": {
|
|
"console": {
|
|
"class": "logging.StreamHandler",
|
|
"formatter": "verbose",
|
|
},
|
|
},
|
|
"root": {"handlers": ["console"], "level": "INFO"},
|
|
"loggers": {
|
|
"apps.integration": {"level": "DEBUG", "propagate": True},
|
|
},
|
|
}
|