Skip to content

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 -- container is a common alternative.

  • autowire (bool, default: False ) –

    when True, inject resolves 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
def __init__(
    self,
    provider: 'ServiceProvider',
    param_name: str = 'provider',
    autowire: bool = False
):
    """
    Args:
        provider: the built ServiceProvider to resolve from.
        param_name: the keyword argument the request scope is passed as in
            the default (non-autowire) mode. Name it to taste -- ``container``
            is a common alternative.
        autowire: when True, ``inject`` resolves registered types by
            annotation instead of passing the scope. Not supported by every
            integration; FastAPI rejects it outright.
    """
    self._provider = provider
    self._param_name = param_name
    self._autowire = autowire

provider property

provider: ServiceProvider

The provider this injector resolves from.

setup

setup(app=None) -> None

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
def setup(self, app=None) -> None:
    """
    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()``.
    """
    global _active_injector
    _active_injector = self

create_scope

create_scope() -> ServiceScope

Create a new, unbound dependency scope.

Source code in packages/depi-core/depi/integration.py
def create_scope(self) -> 'ServiceScope':
    """Create a new, unbound dependency scope."""
    return self._provider.create_scope()

current_scope

current_scope() -> ServiceScope

Return the scope bound to the current request context.

Raises:

Source code in packages/depi-core/depi/integration.py
def current_scope(self) -> 'ServiceScope':
    """
    Return the scope bound to the current request context.

    Raises:
        NoActiveScopeError: if setup(app) never ran, or this is called
            outside a request.
    """
    return current_scope()

inject

inject(fn: Callable) -> Callable

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
def inject(self, fn: Callable) -> Callable:
    """
    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.
    """
    return self._make_inject_wrapper(fn)

DepiScopeMiddleware

DepiScopeMiddleware(get_response)

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
def DepiScopeMiddleware(get_response):
    """
    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.
    """
    if iscoroutinefunction(get_response):

        async def async_middleware(request):
            scope = get_active_injector().create_scope()
            token = set_current_scope(scope)
            try:
                return await get_response(request)
            finally:
                reset_current_scope(token)
                await scope.__aexit__(None, None, None)

        markcoroutinefunction(async_middleware)
        return async_middleware

    def sync_middleware(request):
        scope = get_active_injector().create_scope()
        token = set_current_scope(scope)
        try:
            return get_response(request)
        finally:
            reset_current_scope(token)
            scope.dispose()

    return sync_middleware

NoInjectorRegisteredError

Bases: RuntimeError

Raised when DepiScopeMiddleware runs before any injector registered itself.