Django adapter¶
pip install pydepi-django — import as depi_django. Usage guide:
Django integration.
DjangoInjector
¶
DjangoInjector(provider: ServiceProvider, param_name: str = 'provider', autowire: bool = False)
Bases: BaseInjector
Per-request dependency scopes for a Django project.
Example
injector = DjangoInjector(provider) injector.setup()
@injector.inject def my_view(request, provider): return JsonResponse(provider.resolve(DataService).payload())
With autowire=True the view takes services directly::
@injector.inject
def my_view(request, service: DataService):
return JsonResponse(service.payload())
Parameters:
-
provider(ServiceProvider) –the built ServiceProvider to resolve from.
-
param_name(str, default:'provider') –the keyword argument the request scope is passed as in the default (non-autowire) mode. Name it to taste --
containeris a common alternative. -
autowire(bool, default:False) –when True,
injectresolves registered types by annotation instead of passing the scope. Not supported by every integration; FastAPI rejects it outright.
Source code in packages/depi-core/depi/integration.py
setup
¶
Register this injector as the one DepiScopeMiddleware resolves from.
Django has no application object to attach to, so app is accepted
and ignored to keep the integration interface uniform. Call this from
AppConfig.ready().
Source code in packages/depi-django/depi_django/__init__.py
create_scope
¶
create_scope() -> ServiceScope
current_scope
¶
current_scope() -> ServiceScope
Return the scope bound to the current request context.
Raises:
-
NoActiveScopeError–if setup(app) never ran, or this is called outside a request.
Source code in packages/depi-core/depi/integration.py
inject
¶
Decorator handing the request scope to fn.
Default mode passes the scope as the param_name keyword argument.
With autowire=True, parameters annotated with registered types are
resolved and passed individually instead.
Uses functools.wraps, so it composes inside a decorator stack (route registration, auth, response handling) without losing the wrapped function's identity.
Source code in packages/depi-core/depi/integration.py
DepiScopeMiddleware
¶
Django middleware opening a dependency scope per request.
Returns a sync or async middleware to match get_response, so it does not
force Django to adapt between the two.
Source code in packages/depi-django/depi_django/__init__.py
NoInjectorRegisteredError
¶
Bases: RuntimeError
Raised when DepiScopeMiddleware runs before any injector registered itself.