Skip to content

Flask adapter

pip install pydepi-flask — import as depi_flask. Usage guide: Flask integration.

FlaskInjector

FlaskInjector(provider: ServiceProvider, param_name: str = 'provider', autowire: bool = False)

Bases: BaseInjector

Per-request dependency scopes for a Flask app.

Example

injector = FlaskInjector(provider) injector.setup(app)

@app.route('/data/') @injector.inject def get_data(key, provider): return provider.resolve(DataService).get(key)

With autowire=True, registered types are resolved by annotation instead::

injector = FlaskInjector(provider, autowire=True)

@app.route('/data/<key>')
@injector.inject
def get_data(key, service: DataService):
    return service.get(key)

key is left for Flask to fill from the URL rule, because DataService is registered and str is not.

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

Install before/teardown request hooks on app.

Source code in packages/depi-flask/depi_flask/__init__.py
def setup(self, app) -> None:
    """Install before/teardown request hooks on ``app``."""

    @app.before_request
    def _open_depi_scope():
        scope = self.create_scope()
        setattr(g, _SCOPE_KEY, scope)
        setattr(g, _TOKEN_KEY, set_current_scope(scope))

    @app.teardown_request
    def _close_depi_scope(exception=None):
        token = g.pop(_TOKEN_KEY, None)
        scope = g.pop(_SCOPE_KEY, None)
        if token is not None:
            reset_current_scope(token)
        if scope is not None:
            scope.dispose()

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)