Python DDD Framework
Build modular Python applications with explicit domain boundaries, transactional application services, and a consistent path from local development to deployment.
Python DDD Framework combines a module system with FastAPI, Dishka, Pydantic, SQLAlchemy, PostgreSQL, and Redis. It includes the pddd CLI and project templates, so you can create an application, add business modules, manage their database migrations, and run the same application through HTTP, background jobs, or direct service calls.
Python 3.12–3.14 · Windows and Linux · Async application services · Typed public APIs
Features · Quick start · CLI reference · Application development · Deployment · Upgrading · Documentation
Features
| Capability | What you can build with it |
|---|---|
| Modular applications | Declare module dependencies, compose a Host, and run ordered initialization and shutdown with application-local state. |
| Domain-driven design | Define aggregates, value objects, repository contracts, domain events, and optimistic concurrency rules. Map domain entities directly with native SQLAlchemy configuration; keep DTOs separate. |
| Application services | Use typed service contracts and a shared invocation pipeline for validation, authorization, interceptors, auditing, and units of work. |
| Dependency injection | Register services and native Dishka providers, discover implementations within module-owned packages, and manage application, request, and action scopes. |
| Configuration | Bind YAML and environment inputs to typed Options, validate them at composition time, and inspect configuration sources with sensitive values redacted. |
| HTTP APIs | Expose selected application services through FastAPI, or write explicit routers. Use OpenAPI, filters, file uploads, downloads, and streaming responses. |
| Persistence and events | Use async SQLAlchemy repositories, explicit transaction boundaries, module-owned Alembic migrations, seed contributors, and local events before or after commit. |
| Identity and permissions | Add JWT authentication, refresh sessions, users and roles, permission definitions, and authorization on service methods. |
| Cache, settings, and locks | Use typed Redis caching, global runtime settings with conditional updates and reset, and explicit Redis-backed business locks. |
| Background execution | Enqueue durable PostgreSQL jobs with typed payloads, schedule recurring work, run periodic workers, and select in-process or managed subprocess execution. |
| Real-time communication | Add authenticated WebSocket connections, typed messages, and targeted notifications to connected clients. |
| Hosting and observability | Manage long-lived integrations with HostedService, coordinate shutdown, and use structured logging, correlation, OpenTelemetry tracing, and lifecycle health endpoints. |
| Developer tooling | Generate projects and business modules, inspect composition, run local infrastructure, and reuse TestApplication for application tests. |
The Module owns a feature and its dependencies. The Host composes modules, selects providers, and supplies configuration. Your application owns the generated source code and database migrations.
Runtime integrations ship in the base package; the Host explicitly enables the modules it needs. Installing the package does not start database connections, workers, or trace export. Local events stay within an application process, and WebSocket notifications do not include a distributed backplane or offline replay.
Quick start
Prerequisites
- A supported Python interpreter; the examples use Python 3.12.
- uv for tool installation, dependency management, and project commands.
- Docker with Compose, running locally, for the generated application's PostgreSQL and Redis services.
The supported versions and dependencies are defined in pyproject.toml. The framework, CLI, and bundled templates share one package version.
Read the target artifact's guides before upgrading. Use the local-wheel route below when consuming this checkout; consult current limits for open risks.
1. Install the CLI and create a project
For a published release:
uv tool install --python 3.12 "python-ddd-framework[developer-kit]"
pddd new my-app --python 3.12
cd my-app
To select a specific release, append ==<version> to the quoted package requirement. pddd new creates the Host, configuration, tests, deployment files, and four application documents: README.md, AGENTS.md, docs/architecture.md, and docs/development.md. Python metadata, configuration, environment, source, tests, and deployment files live in backend/; root scripts/ belongs to the consumer. It then runs uv sync inside backend/ and pins both the runtime dependency and developer tools to the CLI's exact framework version. The destination directory must not already exist. --python accepts a supported portable major.minor[.patch] version. --no-sync writes files only and works without that interpreter installed; later enter backend/ and run uv sync to create the target environment. Native uv/test/build and Docker commands run from backend/.
Using an unreleased local wheel
Obtain a wheel built from the checkout you want to evaluate. Replace <absolute-wheel-path> with its full .whl path, and use the same wheel for the CLI and the generated application:
uv tool install --python 3.12 "<absolute-wheel-path>[developer-kit]"
pddd new my-app --framework-wheel "<absolute-wheel-path>"
cd my-app
The generator checks that the wheel contains python-ddd-framework at the CLI's version, copies it into the application's backend/vendor/ directory, and records the local dependency source. Installing a CLI from source alone does not change where generated applications obtain their framework dependency.
2. Prepare infrastructure and add a business module
Run installed pddd project commands from the application root, backend/, or any descendant directory. They locate Host metadata and use the backend's environment and framework version; unrelated nested Python projects do not take ownership:
pddd dev-init
pddd add module orders --template ddd
pddd add module conversions --template basic
dev-init starts or reuses local PostgreSQL and Redis using backend/app.development.yaml. It preserves existing data; database migration and seeding are separate steps.
add module orders generates a DDD skeleton named orders and registers its Application, SQLAlchemy, and HttpApi Modules with the Host. It retains all responsibility directories, package markers, lifecycle hooks, native mapping discovery, migration registration, and a module README. It creates no business entities, services, tables, endpoints, tasks, or test cases. Add them from confirmed requirements. The complete business implementation is available as a standalone Framework Demo, outside the runtime wheel.
ddd is the default six-layer template. basic generates only a Module, a synchronous Protocol service, its transient implementation, and an English README. It has no database/Redis requirement or implicit HTTP/interception. Both templates support --dry-run and refuse existing targets.
3. Initialize the database
Apply the provider migrations selected by the generated Host:
pddd db upgrade --module identity
pddd db upgrade --module settings
pddd db upgrade --module auditing
pddd db upgrade --module background_jobs
pddd db seed --module identity
An empty DDD skeleton retains model and migration registration but has no business tables or revisions. Add actual models before generating a business revision; migration commands still use the configured database. For a module named orders:
pddd db revision --module orders
Review the generated revision in backend/src/modules/orders/sqlalchemy/migrations/ before applying it. Run seed only after declaring the intended contributors:
pddd db upgrade --module orders
pddd db status --module orders
pddd db seed --module orders
Migration commands operate on the selected module. When a migration requires another module's revision, upgrade that prerequisite explicitly. Starting the Host does not migrate or seed the database.
4. Run the application and explore the API
pddd dev
Open http://127.0.0.1:8000/docs. Use the generated identity.seed_admin_username and identity.seed_admin_password in backend/app.development.yaml to call /api/auth/login, then enter the returned access token in Swagger's Authorize dialog.
The empty orders skeleton contributes no business routes. The independent Framework Demo supplies /api/orders, approval and queued approval, file transfer, and an authenticated WebSocket at /ws/orders; use its explicit migration and Seed instructions when you want to explore those capabilities.
For C++ computation, the independent native integration example demonstrates an installed nanobind package, typed application-service consumption, cancellation cleanup, source rebuilds, and artifact delivery. It is outside the runtime wheel and does not change the CLI or default templates. Platform requirements and current limits are described in the example guide and current limits.
The default business API prefix is /api. Liveness and readiness are exposed at /health/live and /health/ready; readiness describes application lifecycle state, not continuous database or Redis health.
CLI reference
Use pddd to create a project. Inside an existing project, use pddd so commands run with that project's framework version.
| Command | Purpose |
|---|---|
pddd new my-app |
Generate a new Host project and install its dependencies. |
pddd add module orders |
Generate a business module and register its packages and Host dependencies. |
pddd dev-init |
Prepare the local PostgreSQL and Redis services from development configuration. |
pddd dev |
Start the development web server with reload at 127.0.0.1:8000. |
pddd db revision --module orders |
Generate an Alembic revision for the module's models. Review it before applying. |
pddd db upgrade --module orders |
Apply the selected module's migrations. |
pddd db status --module orders |
Check that the database is at the selected module's migration heads; fail if it is not. |
pddd db seed --module orders |
Run the selected module's seed contributors after checking its migrations. |
pddd inspect |
Print the composed module graph, service registrations, and redacted configuration inputs as JSON. |
Common variations:
pddd new my-app --dry-run
pddd add module billing --dry-run
pddd dev --host 127.0.0.1 --port 8080
pddd inspect --environment development
pddd db status --module orders --environment production
Generation supports --dry-run without writing files. Database commands require --module; aliases come from installed python_ddd_framework.modules entry points and must belong to the current application's module graph.
Recovering a failed module addition
add module prints a recovery directory under the identified backend's
.python-ddd-framework/generation/<operation-id>/. It retains original bytes, proposed
startup/metadata files, a module file manifest, step records and uv-sync.log. The rendered
template and any unfinished sibling copies are retained too. Open that operation's
RECOVERY.md for its paths and a copyable, read-only inspection procedure.
Stop other generators and editors before recovery. Compare the actual files with the
recorded digests: continue only from the recorded original content, or restore an original
file only while the target still matches this operation's proposed content. Review any
other content manually. Keep generated directories and markers until you explicitly decide
what to do with them; rerunning add module does not repair a partial publication.
When all project files match the proposed contents but installation failed, use the
independent sync script in that operation's RECOVERY.md. Run it with python -I as
instructed. It clears the CLI's recorded Python/uv environment overrides before running
uv sync in the identified backend, including overrides set after generation. A bare
uv sync --directory still inherits environment overrides and can select another
virtual environment. The retry preserves your shell environment and the original records.
File publication and installation have separate results. An interrupted or missing step record requires checking the files; it does not prove that the write failed. The CLI does not automatically restore, move or delete the failure site, roll back the environment or lockfile, or guarantee a transaction across files or power-loss recovery.
Project command environment
db and inspect use --environment, then PYTHON_DDD_FRAMEWORK_ENVIRONMENT, then development. dev always selects development, and dev-init is restricted to development infrastructure.
inspect builds and closes the application without starting services or running migrations. Its output describes a newly composed Host, not a running process. Configuration output contains input values and their sources; it does not include Options defaults or later module contributions.
For the complete options supported by your installed version:
pddd
pddd new --help
pddd add module --help
pddd db --help
pddd inspect --help
Consumer documentation resources
Framework distributions carry python_ddd_framework/consumer_docs/README.md, architecture.md, and development.md: capability navigation, public contracts, and usage respectively. Each capability links to both its contract and its usage. These are installed-package resource paths, not paths relative to a consumer application. New projects contain the isolated lookup procedure in docs/development.md#framework-documentation; their root AGENTS starts with the framework reference. Confirm resource availability in the installed artifact.
Existing applications adopt this layout deliberately:
- Locate consumer_docs in the selected framework artifact and follow its installation or upgrade instructions. Keep the application's own dependencies and source overrides. Matching version strings alone do not establish identical artifacts.
- Preserve the current project/module Markdown and its business decisions. Add the template's framework reference to root AGENTS and the isolated lookup procedure to project development. These links show the bootstrap text only; obtain it from the actual target artifact when adapting an older application.
- Add the matching package-resource references to project README/architecture/development and each module README. Root documents link to
docs/development.md#framework-documentation, project architecture links todevelopment.md#framework-documentation, and module README links to../../../../docs/development.md#framework-documentation. - Compare existing framework paragraphs with the installed guides before removing duplicates. Retain confirmed application rules and initial setup instructions; resolve conflicts rather than choosing or overwriting either side. Record actual capability choices in the module README.
- Execute the lookup through
backend/.venvwith-I -B, verify the installed version/source against project metadata, and follow the relevant contract and usage. Missing environment, resource, chapter or mismatched source is an explicit failure, not permission to read main/latest or install dependencies.
The source templates, application files and installed framework resources have different owners. Updates replace package guides, not generated Markdown or business code; there is no document synchronizer or reserved editable-region protocol. The root framework README owns the current installation and upgrade procedure and is carried in the distribution's METADATA, readable using the installed guide procedure. Public resource paths and anchors are stable documentation entry points; changes require an explicit contract decision and coordinated reference updates.
Application development
Find the right place for a change
The generated project starts with backend/src/host/ for composition and startup. Modules live under backend/src/modules/. A basic module contains module.py, contracts/, services/, and its README. The default ddd module has these responsibilities:
| Location within a module | Responsibility |
|---|---|
domain_shared/ |
Shared values, errors, and permission names. |
domain/ |
Aggregates, business rules, events, repository contracts, settings, and seed contributors. |
application_contracts/ |
DTOs and public application-service contracts. |
application/ |
Use-case orchestration, service implementations, event handlers, jobs, and workers. |
sqlalchemy/ |
Native mappings of domain entities, repository implementations, and migrations. |
http_api/ |
Service exposure, explicit routes, file transfer, and WebSocket endpoints. |
tests/ |
Tests owned by the business module; excluded from the production wheel. |
For a new use case, define its input and output in application_contracts/, put business rules in domain/, and coordinate the work in application/. Persist through a repository contract. The HTTP module selects which application services to expose; the Host selects infrastructure providers.
For a model change, update the domain declaration and any explicit storage configuration in sqlalchemy/mappings/. With map_entity, supported ordinary fields are inferred without changing the mapping callback; special storage remains explicit. Generate and review the revision, then run db upgrade for that module. For another business module, repeat the add module, db revision, db upgrade, and db seed steps. Add application-specific dependencies with uv add <package> from backend/.
Use the installed development guide for service registration, typed invocation, HTTP declarations, transactions, background handlers, and distributed locks. Locate it in the application's backend environment using consumer documentation resources.
Configure the application
Edit backend/app.development.yaml for local connections, identity settings, logging, and module Options. An optional backend/app.yaml can hold shared configuration. Environment variables override file inputs; generated Hosts use the PDDD_ prefix and __ between nested fields. For example, PDDD_HTTP__API_PREFIX=/v1 changes the business API prefix.
PYTHON_DDD_FRAMEWORK_ENVIRONMENT selects the Host environment; it is separate from business configuration. Typed Options validate configuration during application composition. Use pddd inspect to investigate input values and where they came from.
Generated credentials are for local development. Production configuration is supplied separately in app.production.yaml. Follow the installed guides for Options and settings, background work, and observability.
Use global settings
Declare a typed SettingDefinition and its scanned provider under the owning module's domain/settings/, then add SettingsModule to that module's dependencies. Inject SettingProvider to read values and SettingManager for conditional writes/reset. The generated Host already selects Settings persistence and management HTTP; apply its Settings migration before using the store for reads or writes.
Values resolve from runtime override, Host configuration, then definition default. Reset clears an override and resumes fallback. Management provides list/read/update/reset with visibility, permissions, and version checks; business code decides when to use the value. Follow the installed Global settings guide for declarations, configuration, permissions, and request bodies.
Run application tests
After completing local database setup, run from backend/:
uv run pytest
The generated application includes Host tests. DDD modules contain only a test package marker; business tests belong to the application or the independent order example. Keep Docker available for Host tests that use real infrastructure. For custom application tests, the framework's TestApplication reuses the normal application builder and typed service invocation. Framework contributor checks are documented separately in framework validation.
Deployment
Generated applications include backend/Dockerfile and backend/compose.production.yaml. Run build and deployment commands from backend/:
uv build --no-sources
For container deployment:
- Supply
app.production.yamlwith production connections and credentials; keep it out of source control and the image. The generated Compose file mounts it read-only for both migration and web services. - Build and validate the application image, then set
APP_IMAGEto that image's immutable digest. - Run database upgrades for each required module in dependency order. Run initial seed operations explicitly with
--environment production. - Start the web service from the same image and check its health endpoints.
The image uses python -m host.main without development reload. Runtime installations use the base framework package; developer-kit is only needed for generation. Follow the generated application's README for deployment commands and the installed deployment guide for framework boundaries.
Upgrading
Framework upgrades update dependencies and installed package guides. They do not regenerate application Markdown, business code, Host configuration or database migrations. Updating a global CLI also leaves existing projects unchanged.
- Read the target artifact's consumer changelog, README and consumer guides. Review every intervening version's required actions. Check the capabilities in use, public contracts, enablement requirements and application-specific data migration needs.
- Pin both the runtime dependency and the developer-kit dependency to the same target version. Preserve application dependencies and unrelated source overrides. If selecting PyPI instead of a local wheel or Git source, remove only the framework entry in tool.uv.sources.
- Deliberately adapt affected application code, configuration and local documentation. From backend/, update the environment and run the application's authorized checks:
uv lock --upgrade-package python-ddd-framework
uv sync --locked
uv run pytest
uv build --no-sources
During 0.x, compatible fixes use a patch release; changes requiring consumer adaptation use a minor release. Publishing changed package contents requires a new version. Package installation does not migrate business data; review and execute required database operations explicitly.
Documentation
The installed package provides the English capability index, public contracts and usage guide. Each capability links to both its contract and usage. Use the actual installed resources when developing an application.
Generated applications maintain their own README, AGENTS, architecture and development guides; each module maintains its README. They own application facts and link to the installed framework guides through the isolated lookup procedure. Upgrades do not overwrite them. Installed templates and framework checkouts are read-only references; equal version strings do not prove equal artifacts.
The Chinese engineering guides require source repository access:
| If you need to… | Read |
|---|---|
| Change framework implementation or validation | Maintainer guide |
| Locate capability owners and implementation invariants | Internal architecture |
| Understand an effective design decision | Decision index |
| Check open risks and current limits | Current limits |
| Locate a historical change | Git history lookup |
| Work on the framework | Contributor guidance and focused reading paths |
License
Python DDD Framework and the repository's own examples/templates use the MIT License, retaining Copyright (c) 2026 hank-repo. Third-party notices remain with their code, including the PgQueuer upstream license in the installed package. Template licensing does not choose a license for a generated application's own business code. The source repository remains private; public PyPI wheel/sdist artifacts are the delivery channel.
The same-version sdist includes the complete Framework Demo; the runtime wheel contains only the framework package and its existing resources. In an installed application, read python_ddd_framework/consumer_docs/README.md#demo for the version-specific PyPI download procedure. Demo setup, explicit migrations/Seed, Web and Worker entry points are self-contained in that artifact.
Metadata
Release files for python-ddd-framework 0.11.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| python_ddd_framework-0.11.1.tar.gz | 717.8 kB | Without provenance | Details for python_ddd_framework-0.11.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| python_ddd_framework-0.11.1-py3-none-any.whl | Python 3 | none | any | Details for python_ddd_framework-0.11.1-py3-none-any.whl |
Total release size: 1.4 MB
Release files / python_ddd_framework-0.11.1.tar.gz
| Download URL | python_ddd_framework-0.11.1.tar.gz |
|---|---|
| Size | 717.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bfdd0b691cb69f449a3b94cd654da0f486cbe1a12ef07aefc13b6838e8248e4a
|
|
BLAKE2b-256 checksum How to use checksums |
bd75385c3be813a9c57aa5e2e5a804d27379f66b52198e71b10821c62b1b7fc7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / python_ddd_framework-0.11.1-py3-none-any.whl
| Download URL | python_ddd_framework-0.11.1-py3-none-any.whl |
|---|---|
| Size | 712.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
06129a8c79946377af31dbb8a10312267ba1f130a096f790187cfe164d883c76
|
|
BLAKE2b-256 checksum How to use checksums |
81cd6a116d970da0c9f40eefd95024af1d50a9dd03b189dd90c7feccf303b0f6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for python-ddd-framework 0.11.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.