Skip to main content

modern-di-aiohttp

PyPI version Supported Python versions Downloads Coverage CI License GitHub stars uv Ruff ty

modern-di integration for aiohttp.

Full guide: aiohttp integration docs

Usage example: examples/

Installation

uv add modern-di-aiohttp      # or: pip install modern-di-aiohttp

Usage

aiohttp has no dependency-injection system of its own, so modern-di-aiohttp pairs an @inject decorator with inert FromDI markers. setup_di stores the container on the app, opens it on startup and closes it on cleanup, and installs middleware that builds a per-connection child container automatically; FromDI resolves a provider (or type) into a handler parameter.

import dataclasses
import typing

from aiohttp import web
from modern_di import Container, Group, Scope, providers
from modern_di_aiohttp import FromDI, inject, setup_di


@dataclasses.dataclass(kw_only=True)
class Settings:
    debug: bool = True


@dataclasses.dataclass(kw_only=True)
class UserService:
    settings: Settings  # auto-injected by type


class Dependencies(Group):
    settings = providers.Factory(scope=Scope.APP, creator=Settings)
    user_service = providers.Factory(scope=Scope.REQUEST, creator=UserService)


@inject
async def index(
    request: web.Request,
    user_service: typing.Annotated[UserService, FromDI(Dependencies.user_service)],
) -> web.Response:
    return web.json_response({"debug": user_service.settings.debug})


app = web.Application()
app.router.add_get("/", index)
container = Container(groups=[Dependencies])
setup_di(app, container)
container.validate()  # optional fail-fast; must come after setup_di registers its providers

@inject also works on a plain def handler. It returns a sync wrapper for a sync function, so aiohttp handles the decorated handler the same way it handles the undecorated one, including its deprecation warning for sync handlers.

@inject works the same on the methods of a class-based web.View. Decorate the handler method, not the class; aiohttp calls the method with no arguments, so the request is taken from self.request:

class Users(web.View):
    @inject
    async def get(
        self,
        user_service: typing.Annotated[UserService, FromDI(Dependencies.user_service)],
    ) -> web.Response:
        return web.json_response({"debug": user_service.settings.debug})


app.router.add_view("/users", Users)

An HTTP request opens a Scope.REQUEST child container; a WebSocket connection opens a Scope.SESSION one. The connection aiohttp.web.Request is resolvable within DI: HTTP handlers and REQUEST-scoped factories inject it by type via aiohttp_request_provider, while WebSocket handlers read it via FromDI(aiohttp_websocket_provider). For per-message work inside a WebSocket handler, open a nested Scope.REQUEST child of the session container fetched with fetch_request_container.

Sub-apps added with app.add_subapp work with or without their own setup_di. When both the parent and the sub-app call setup_di, a sub-app route resolves from a child of the sub-app's root container, and the parent's middleware still opens and closes its own child container around it. When only the parent calls setup_di, a sub-app route resolves from a child of the parent's root container.

Sharing a container

By default setup_di opens the root container on startup and closes it on cleanup. If the same container also serves an app of another modern-di integration, such as a FastStream consumer, the first app to shut down would close it for the rest. Pass manage_lifespan=False to every setup_di that shares the container and own the root yourself. The middleware still builds and closes a child container per connection. See FastAPI and FastStream sharing a container for the pattern.

import asyncio


async def main() -> None:
    app = web.Application()
    container = Container(groups=[Dependencies])
    setup_di(app, container, manage_lifespan=False)

    async with container:
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, "localhost", 8080)
        await site.start()
        try:
            await asyncio.Event().wait()
        finally:
            await runner.cleanup()

APP-scoped finalizers run once, when the async with block exits.

Shutdown order

setup_di appends the root container's close to app.on_cleanup. These hooks run before the close and can still resolve from the container:

  • on_shutdown handlers
  • cleanup_ctx teardown
  • on_cleanup handlers added before setup_di

on_cleanup handlers added after setup_di run after the close and get ContainerClosedError. Add them before setup_di. If you can't, pass manage_lifespan=False and close the container yourself after runner.cleanup(), as in the example above.

API

Symbol Description
setup_di(app, container, *, manage_lifespan=True) Stores the container on the app, wires on_startup/on_cleanup (reopen on startup, close on cleanup), registers the connection providers, and installs the per-connection middleware. With manage_lifespan=False it skips the on_startup/on_cleanup hooks and never opens or closes the root container (see Sharing a container)
inject(handler) Decorator that resolves every FromDI-marked parameter from the request's child container and passes them to the handler; works on a sync or async def function handler and on a method of a web.View subclass
FromDI(dependency) Inert Annotated marker resolved by @inject; accepts a provider or a type
fetch_di_container(app) Returns the app-scoped root container
fetch_request_container(request) Returns the per-connection child container the middleware built for this request
aiohttp_request_provider ContextProvider for the current aiohttp.web.Request (REQUEST scope)
aiohttp_websocket_provider ContextProvider for the connection aiohttp.web.Request at WebSocket SESSION scope

📦 PyPI

📝 License

Part of modern-python

Built on modern-di, a dependency-injection framework with an IoC container and scopes.

Browse the full list of templates and libraries in modern-python; the org profile has the categorized index.

Metadata

Release files for modern-di-aiohttp 4.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for modern-di-aiohttp 4.2.3
File Size Uploaded Provenance
modern_di_aiohttp-4.2.3.tar.gz 6.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for modern-di-aiohttp 4.2.3
File Interpreter ABI Platform
modern_di_aiohttp-4.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 13.8 kB

Release files / modern_di_aiohttp-4.2.3.tar.gz

Download URL modern_di_aiohttp-4.2.3.tar.gz
Size 6.9 kB
Tags Source
SHA-256 checksum
How to use checksums
100f5d75f0a0b73a7d924da7cca54ea86a14af6045f224b7610a9e1049961f82
BLAKE2b-256 checksum
How to use checksums
3f98550b3a26dd1f0601b43bfd3e420cf3a6dbe45bcf43a6d7687bcda2c29e04
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","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 / modern_di_aiohttp-4.2.3-py3-none-any.whl

Download URL modern_di_aiohttp-4.2.3-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
44c850cf5d123a222c35750aba0af872e61cd4c0210949e778efa394688f84fd
BLAKE2b-256 checksum
How to use checksums
b5db7c8101cf258dfa57823300bce8a8c4f03d0e73d1d523a8d314c67ed65505
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","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 modern-di-aiohttp 4.2.3

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page