Сервис приложения
Сервисы/Python (Django)

Сервис Python (Django)

Среда выполнения Python для веб-приложений и API на Django, миграций, статических файлов и воркеров Celery.

Этот сервис запускает ваш код: его образ собирается из Git-репозитория, а каждая сборка развёртывается в окружение.

В StackMaster

Как Python (Django) работает в StackMaster

What Wodby sets up for an application that runs on this service. Check it before adding a server configuration or connection settings to the code.

How the application is started

The container runs Gunicorn with a configuration file the image writes on every start:

gunicorn -c /usr/local/etc/gunicorn/config.py --pythonpath "$GUNICORN_PYTHONPATH" "$GUNICORN_APP"
  • GUNICORN_APP names the WSGI callable as module:callable. The image default is myapp.wsgi:application; set the variable on the service, or in the Dockerfile, when the application lives elsewhere.
  • Gunicorn listens on 0.0.0.0:8080. The port is fixed in the generated configuration and is the port of the service's HTTP endpoint.
  • The image does not include Gunicorn. It must be one of the application's dependencies.
  • Access and error logs go to the container's output.

Do not add a Gunicorn configuration file to the repository to change workers or timeouts: the container does not load it. Set these variables on the service instead: GUNICORN_WORKERS, GUNICORN_WORKER_CLASS, GUNICORN_WORKER_CONNECTIONS, GUNICORN_TIMEOUT, GUNICORN_KEEPALIVE, GUNICORN_BACKLOG, GUNICORN_LOGLEVEL, GUNICORN_PROC_NAME, GUNICORN_PYTHONPATH. A change applies with the next deployment of the service.

Linked services

Links to other services reach the application as environment variables. Nothing in the image reads them: the application reads them itself. Do not hardcode hosts or credentials.

LinkVariables
Database (MariaDB, MySQL or PostgreSQL)DB_HOST, DB_PORT, DB_NAME (also DB_DATABASE), DB_USERNAME, DB_PASSWORD, DB_DRIVER (also DB_CONNECTION)
MailSMTP_HOST, SMTP_PORT
Redis or ValkeyREDIS_HOST, REDIS_PORT, REDIS_PASSWORD
OpenTelemetry CollectorOTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf), OTEL_EXPORTER_OTLP_HEADERS (the Collector's ingest token)

All links are optional. A variable is present only while its link exists and the linked service is enabled. The mail link carries no credentials. The OpenTelemetry variables are the standard SDK settings: an application or agent that uses an OpenTelemetry SDK exports to the Collector without further configuration; set OTEL_SERVICE_NAME to name the application in traces.

Environment

  • WODBY_HOSTS is a JSON array of the environment's hosts, not a comma-separated string. WODBY_PRIMARY_HOST and WODBY_PRIMARY_URL are the canonical ones for links generated outside a request.
  • WODBY_APP_SERVICE_NAME is this service's host name inside the environment. Other services reach the application at that name on port 8080.
  • WODBY_ENV_TYPE tells a development environment from a production-like one.

Build

The code is copied to /usr/src/app, the working directory. The service's own Dockerfile then runs pip install -r requirements.txt when that file exists, and nothing else. A pipeline that passes a Dockerfile from the repository (wodby ci build python -f Dockerfile) uses that file instead, and the repository's Dockerfile then owns dependency installation. uv is available in the image.

The service declares no volume of its own: files written inside the container are lost when it is replaced.

In a development workspace

  • The checkout is mounted at /usr/src/app and served as it is on disk.
  • Workspace setup installs dependencies with workspace-python prepare: uv sync --locked when uv.lock exists, otherwise pip install -r requirements.txt into a virtual environment. One of the two must exist. Run it again after changing dependencies.
  • The virtual environment is .wodby-workspace/venv in the checkout. .wodby-workspace/ and __pycache__/ are kept out of Git status without touching .gitignore. Use .wodby-workspace/venv/bin/python for commands that need the application's packages.
  • The application is started with python -m gunicorn --bind "$HOST:$PORT" --reload --reload-engine poll "$GUNICORN_APP", with HOST and PORT defaulting to 0.0.0.0 and 8080. The generated Gunicorn configuration and the GUNICORN_* tuning variables are not used here.
  • WORKSPACE_PYTHON_COMMAND on the service replaces that start command. A custom command must do its own reloading.
  • A change to variables or linked services still needs a deployment of the environment.

Check the result

  • curl -s -o /dev/null -w '%{http_code}' localhost:8080 from the container shows whether the application answers on the expected port.
  • printenv | grep -E '^(DB|SMTP|REDIS)_' | cut -d= -f1 lists the link variables that are present.

Django on Wodby

What this service adds to the Python service it is based on. Check it before adding database, secret key or Celery settings to the project.

Variables the service sets

VariableMeaning
GUNICORN_APPmyapp.wsgi:application. Change it on the service when the project package is not named myapp.
CELERY_APPmyapp. The Celery command line reads it to find the application. Change it together with GUNICORN_APP.
DJANGO_SECRET_KEYA secret generated by Wodby for the service. It stays the same across deployments.
DJANGO_DEBUGSet to true in environments of type dev only. Absent in every other type.

Django does not read DJANGO_SECRET_KEY or DJANGO_DEBUG by itself. settings.py must take SECRET_KEY and DEBUG from them. Do not generate or commit another secret key.

Linked services

In addition to the variables of the Python service:

LinkVariable
DatabaseDATABASE_URL, the whole connection as one URL, with credentials
Redis or ValkeyCELERY_BROKER_URL, a redis:// URL with the password, database 0

The service does not write Django settings. settings.py must build DATABASES from DATABASE_URL (or from the DB_* variables), the broker from CELERY_BROKER_URL and mail from SMTP_HOST and SMTP_PORT. Each variable is present only while its link exists, so the settings must work without it. Both URL variables hold a password: never print or commit their values.

Celery worker

The optional django-celery service runs celery worker --loglevel=INFO instead of Gunicorn. It needs celery among the dependencies and a Celery application in the package named by CELERY_APP. The broker comes from the Redis or Valkey link, as CELERY_BROKER_URL.

Before every rollout

Wodby runs two commands for this service in a job of the new version, before its pods are replaced. On the first deployment they run right after the install. If one fails, the deployment stops before the rollout. The previous version keeps serving until the new one is ready, and keeps serving if the deployment fails, so migrations must keep working with the previous version: add columns and tables first, remove or rename them in a later release.

The commands, in this order of declaration:

  1. python manage.py migrate
  2. python manage.py collectstatic --no-input

manage.py must be in the working directory, /usr/src/app, and STATIC_ROOT must be set for the second one. The start command and the pipeline do not have to run them. Nothing in the service serves the collected files: the application serves static files itself.

Host checks

ALLOWED_HOSTS is the project's own setting. The environment's hosts are in WODBY_HOSTS (a JSON array), and the internal host name is in WODBY_APP_SERVICE_NAME.

In a development workspace

Gunicorn runs with its polling reloader, so a saved Python file is picked up without a restart. A change to dependencies needs workspace preparation again. Migrations are not applied by file changes: run manage.py migrate with the workspace's Python.

Check the result

  • python manage.py check loads the settings with the container's environment.
  • python manage.py showmigrations shows whether the database link works and which migrations are applied.

Обзор

Технический профиль Python (Django)

Здесь перечислены версии, которые можно выбрать для Python (Django) в стеке или окружении. Сам сервис публикуется ревизиями, и стек ссылается на конкретную ревизию.

Тип сервиса

Сервис приложения

Версии

3.15, 3.14, 3.13, 3.12, 3.11, 3.10

Стеки

Стеки, в которые входит Python (Django)

Python (Django) входит в этот публичный стек. Можно создать приложение из публичного стека как есть или добавить сервис в собственный стек.

CI/CD

Сборка Python (Django) из Git-репозитория

Начните с публичного шаблона проекта или подключите собственный репозиторий. В StackMaster CI push в ветку, за которой следит окружение, запускает сборку Python (Django), а пайплайн её развёртывает.

Django boilerplate

Используйте его как есть или клонируйте в свой Git-аккаунт.

wodby/django-boilerplate

Git-провайдеры

Репозиторий подключается через интеграцию с его Git-провайдером.

CI-провайдеры

StackMaster CI встроен в платформу: пайплайн описывается в файле .wodby/pipeline.yml в репозитории. Для подключённого репозитория те же шаги может выполнять внешний CI-провайдер с помощью StackMaster CLI.

Реестры контейнеров

Собранные образы по умолчанию попадают в StackMaster Registry или во внешний реестр, подключённый как интеграция.

Переменные окружения из интеграций

Интеграция с переменными один раз сохраняет учётные данные стороннего сервиса. Подключите её к Python (Django), и StackMaster передаст их в контейнер как переменные окружения во время работы, а не при сборке образа.

Конфигурация

Конфигурация сервиса Python (Django)

Сервис Python (Django) объявляет следующее. Если значение можно изменить, его задаёт стек, а каждое окружение может его переопределить.

Технические домены

StackMaster выдаёт каждому публичному HTTP-порту технический домен с TLS-сертификатом и продлевает сертификат. Порт, который сервис помечает как частный, домен не получает. Можно добавить собственные домены.

Действия

2 действия. Действие — это команда, которую вы запускаете из панели управления или которую StackMaster выполняет после развёртывания или обновления стека.

Связи сервиса

Каждая связь — это подключение Python (Django) к другому сервису. На какой сервис указывает связь, задаёт стек. На карточках перечислены публичные сервисы, которые подходят для каждой связи.

redis

Сервисы, которые подходят для этой связи

sendmail

Сервисы, которые подходят для этой связи