modern-di-fastapi 0.3.0__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: modern-di-fastapi
3
- Version: 0.3.0
3
+ Version: 0.4.1
4
4
  Summary: Modern-DI integration for FastAPI
5
5
  Project-URL: repository, https://github.com/modern-python/modern-di
6
6
  Project-URL: docs, https://modern-di.readthedocs.io
@@ -0,0 +1,9 @@
1
+ from modern_di_fastapi.main import Provide, build_di_container, fetch_di_container, setup_di
2
+
3
+
4
+ __all__ = [
5
+ "Provide",
6
+ "build_di_container",
7
+ "fetch_di_container",
8
+ "setup_di",
9
+ ]
@@ -1,15 +1,17 @@
1
1
  import dataclasses
2
+ import enum
2
3
  import typing
3
4
 
4
5
  import fastapi
5
6
  from modern_di import Container, Scope, providers
7
+ from starlette.requests import HTTPConnection
6
8
 
7
9
 
8
10
  T_co = typing.TypeVar("T_co", covariant=True)
9
11
 
10
12
 
11
- def setup_di(app: fastapi.FastAPI) -> Container:
12
- app.state.di_container = Container(scope=Scope.APP)
13
+ def setup_di(app: fastapi.FastAPI, scope: enum.IntEnum = Scope.APP) -> Container:
14
+ app.state.di_container = Container(scope=scope)
13
15
  return app.state.di_container
14
16
 
15
17
 
@@ -17,9 +19,17 @@ def fetch_di_container(app: fastapi.FastAPI) -> Container:
17
19
  return typing.cast(Container, app.state.di_container)
18
20
 
19
21
 
20
- async def _build_request_container(request: fastapi.Request) -> typing.AsyncIterator[Container]:
21
- container: Container = fetch_di_container(request.app)
22
- async with container.build_child_container(context={"request": request}) as request_container:
22
+ async def build_di_container(connection: HTTPConnection) -> typing.AsyncIterator[Container]:
23
+ context: dict[str, typing.Any] = {}
24
+ scope: Scope | None = None
25
+ if isinstance(connection, fastapi.Request):
26
+ scope = Scope.REQUEST
27
+ context["request"] = connection
28
+ elif isinstance(connection, fastapi.WebSocket):
29
+ context["websocket"] = connection
30
+ scope = Scope.SESSION
31
+ container: Container = fetch_di_container(connection.app)
32
+ async with container.build_child_container(context=context, scope=scope) as request_container:
23
33
  yield request_container
24
34
 
25
35
 
@@ -28,7 +38,7 @@ class Dependency(typing.Generic[T_co]):
28
38
  dependency: providers.AbstractProvider[T_co]
29
39
 
30
40
  async def __call__(
31
- self, request_container: typing.Annotated[Container, fastapi.Depends(_build_request_container)]
41
+ self, request_container: typing.Annotated[Container, fastapi.Depends(build_di_container)]
32
42
  ) -> T_co:
33
43
  return await self.dependency.async_resolve(request_container)
34
44
 
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "modern-di-fastapi"
3
+ description = "Modern-DI integration for FastAPI"
4
+ authors = [{ name = "Artur Shiriev", email = "me@shiriev.ru" }]
5
+ requires-python = ">=3.10,<4"
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ keywords = ["DI", "dependency injector", "ioc-container", "FastAPI", "python"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3.10",
11
+ "Programming Language :: Python :: 3.11",
12
+ "Programming Language :: Python :: 3.12",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Typing :: Typed",
15
+ "Topic :: Software Development :: Libraries",
16
+ ]
17
+ dependencies = ["fastapi>=0.100", "modern-di"]
18
+ dynamic = ["version"]
19
+
20
+ [project.urls]
21
+ repository = "https://github.com/modern-python/modern-di"
22
+ docs = "https://modern-di.readthedocs.io"
23
+
24
+ [dependency-groups]
25
+ dev = ["httpx", "asgi-lifespan"]
26
+
27
+ [build-system]
28
+ requires = ["hatchling", "hatch-vcs"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.version]
32
+ source = "vcs"
33
+ raw-options.root = "../.."
34
+ fallback-version = "0"
35
+
36
+ [tool.hatch.build]
37
+ include = ["modern_di_fastapi"]
38
+
39
+ [tool.pytest.ini_options]
40
+ addopts = "--cov=. --cov-report term-missing"
41
+ asyncio_mode = "auto"
42
+
43
+ [tool.coverage.report]
44
+ exclude_also = ["if typing.TYPE_CHECKING:"]
@@ -1,18 +0,0 @@
1
- default: install lint test
2
-
3
- install:
4
- uv lock --upgrade
5
- uv sync --all-extras --frozen
6
-
7
- lint:
8
- uv run ruff format .
9
- uv run ruff check . --fix
10
- uv run mypy .
11
-
12
- lint-ci:
13
- uv run ruff format . --check
14
- uv run ruff check . --no-fix
15
- uv run mypy .
16
-
17
- test *args:
18
- uv run pytest {{ args }}
@@ -1,8 +0,0 @@
1
- from modern_di_fastapi.main import Provide, fetch_di_container, setup_di
2
-
3
-
4
- __all__ = [
5
- "Provide",
6
- "fetch_di_container",
7
- "setup_di",
8
- ]
@@ -1,87 +0,0 @@
1
- [project]
2
- name = "modern-di-fastapi"
3
- description = "Modern-DI integration for FastAPI"
4
- authors = [
5
- { name = "Artur Shiriev", email = "me@shiriev.ru" },
6
- ]
7
- readme = "README.md"
8
- requires-python = ">=3.10,<4"
9
- license = "MIT"
10
- keywords = ["DI", "dependency injector", "ioc-container", "FastAPI", "python"]
11
- classifiers = [
12
- "Programming Language :: Python :: 3.10",
13
- "Programming Language :: Python :: 3.11",
14
- "Programming Language :: Python :: 3.12",
15
- "Programming Language :: Python :: 3.13",
16
- "Typing :: Typed",
17
- "Topic :: Software Development :: Libraries",
18
- ]
19
- packages = [
20
- { include = "modern_di_fastapi" },
21
- ]
22
- dynamic = ["version"]
23
- dependencies = [
24
- "fastapi>=0.100",
25
- "modern-di",
26
- ]
27
-
28
- [project.urls]
29
- repository = "https://github.com/modern-python/modern-di"
30
- docs = "https://modern-di.readthedocs.io"
31
-
32
- [dependency-groups]
33
- dev = [
34
- "httpx",
35
- "pytest",
36
- "pytest-cov",
37
- "pytest-asyncio",
38
- "ruff",
39
- "mypy",
40
- "typing-extensions",
41
- "asgi-lifespan",
42
- ]
43
-
44
- [build-system]
45
- requires = ["hatchling", "hatch-vcs"]
46
- build-backend = "hatchling.build"
47
-
48
- [tool.hatch.version]
49
- source = "vcs"
50
- fallback-version = "0"
51
-
52
- [tool.mypy]
53
- python_version = "3.10"
54
- strict = true
55
-
56
- [tool.ruff]
57
- fix = true
58
- unsafe-fixes = true
59
- line-length = 120
60
- target-version = "py310"
61
- extend-exclude = [
62
- "docs",
63
- ]
64
-
65
- [tool.ruff.lint]
66
- select = ["ALL"]
67
- ignore = [
68
- "D1", # allow missing docstrings
69
- "S101", # allow asserts
70
- "TCH", # ignore flake8-type-checking
71
- "FBT", # allow boolean args
72
- "ANN101", # missing-type-self
73
- "ANN102", # missing-type-cls
74
- "D203", # "one-blank-line-before-class" conflicting with D211
75
- "D213", # "multi-line-summary-second-line" conflicting with D212
76
- "COM812", # flake8-commas "Trailing comma missing"
77
- "ISC001", # flake8-implicit-str-concat
78
- ]
79
- isort.lines-after-imports = 2
80
- isort.no-lines-before = ["standard-library", "local-folder"]
81
-
82
- [tool.pytest.ini_options]
83
- addopts = "--cov=. --cov-report term-missing"
84
- asyncio_mode = "auto"
85
-
86
- [tool.coverage.report]
87
- exclude_also = ["if typing.TYPE_CHECKING:"]
File without changes
@@ -1,65 +0,0 @@
1
- import contextlib
2
- import dataclasses
3
- import typing
4
-
5
- import fastapi
6
- import httpx
7
- import pytest
8
- from asgi_lifespan import LifespanManager
9
- from modern_di import Scope, providers
10
- from starlette import status
11
- from starlette.requests import Request
12
-
13
- from modern_di_fastapi import Provide, setup_di
14
-
15
-
16
- @contextlib.asynccontextmanager
17
- async def lifespan(app_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
18
- container = setup_di(app_)
19
- async with container:
20
- yield
21
-
22
-
23
- app = fastapi.FastAPI(lifespan=lifespan)
24
-
25
-
26
- @dataclasses.dataclass(kw_only=True, slots=True)
27
- class SimpleCreator:
28
- dep1: str
29
-
30
-
31
- @dataclasses.dataclass(kw_only=True, slots=True)
32
- class DependentCreator:
33
- dep1: SimpleCreator
34
-
35
-
36
- def context_adapter_function(*, request: Request, **_: object) -> str:
37
- return request.method
38
-
39
-
40
- app_factory = providers.Factory(Scope.APP, SimpleCreator, dep1="original")
41
- request_factory = providers.Factory(Scope.REQUEST, DependentCreator, dep1=app_factory.cast)
42
- context_adapter = providers.ContextAdapter(Scope.REQUEST, context_adapter_function)
43
-
44
-
45
- @app.get("/")
46
- async def read_root(
47
- app_factory_instance: typing.Annotated[SimpleCreator, Provide(app_factory)],
48
- request_factory_instance: typing.Annotated[DependentCreator, Provide(request_factory)],
49
- method: typing.Annotated[str, Provide(context_adapter)],
50
- ) -> str:
51
- assert isinstance(app_factory_instance, SimpleCreator)
52
- assert isinstance(request_factory_instance, DependentCreator)
53
- return method
54
-
55
-
56
- @pytest.fixture(scope="session")
57
- async def client() -> typing.AsyncIterator[httpx.AsyncClient]:
58
- async with LifespanManager(app):
59
- yield httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")
60
-
61
-
62
- async def test_read_main(client: httpx.AsyncClient) -> None:
63
- response = await client.get("/")
64
- assert response.status_code == status.HTTP_200_OK
65
- assert response.json() == "GET"