fastapi-injected 0.1.4__tar.gz → 0.2.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.
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/PKG-INFO +58 -2
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/README.md +55 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/__init__.py +8 -0
- fastapi_injected-0.2.1/fastapi_injected/_deps_tp.py +63 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/_fastapi_lifecycle.py +22 -8
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/deps.py +49 -11
- fastapi_injected-0.2.1/fastapi_injected/overrides.py +122 -0
- fastapi_injected-0.2.1/fastapi_injected/resolve.py +56 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/scope.py +9 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/types.py +11 -2
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/pyproject.toml +3 -1
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/deps.py +10 -0
- fastapi_injected-0.2.1/tests/test_fastapi.py +121 -0
- fastapi_injected-0.2.1/tests/test_overrides.py +107 -0
- fastapi_injected-0.2.1/tests/test_resolve.py +67 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/uv.lock +206 -163
- fastapi_injected-0.1.4/fastapi_injected/resolve.py +0 -26
- fastapi_injected-0.1.4/tests/test_fastapi.py +0 -35
- fastapi_injected-0.1.4/tests/test_resolve.py +0 -32
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.github/dependabot.yml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.github/workflows/automerge.yml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.github/workflows/lint.yml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.github/workflows/publish.yml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.github/workflows/test.yml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.gitignore +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/.pre-commit-config.yaml +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/LICENSE +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/inject.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/fastapi_injected/sign.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/__init__.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/ext/__init__.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/ext/test_pydantic_ai.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/test_inject.py +0 -0
- {fastapi_injected-0.1.4 → fastapi_injected-0.2.1}/tests/test_typing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: fastapi-injected
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Yet another library to reuse fastapi dependency injection
|
|
5
5
|
Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
|
|
6
6
|
Author-email: Yurii Karabas <1998uriyyo@gmail.com>
|
|
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
16
16
|
Requires-Python: >=3.12
|
|
17
17
|
Requires-Dist: fastapi>=0.139.2
|
|
18
18
|
Requires-Dist: typing-extensions>=4.16.0
|
|
19
|
+
Requires-Dist: typing-inspection>=0.4.4
|
|
19
20
|
Description-Content-Type: text/markdown
|
|
20
21
|
|
|
21
22
|
# fastapi-injected
|
|
@@ -116,6 +117,61 @@ async with push_inject_scope():
|
|
|
116
117
|
|
|
117
118
|
Use `@inject(new_scope=True)` to opt a function out of the surrounding scope and always get fresh dependencies.
|
|
118
119
|
|
|
120
|
+
### Overriding dependencies
|
|
121
|
+
|
|
122
|
+
`push_overrides` swaps dependencies out for the duration of a `with` block — handy in tests, or anywhere you need to run the same code against a different implementation:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from fastapi_injected import push_overrides
|
|
126
|
+
|
|
127
|
+
with push_overrides({Session: Session(closed=True)}):
|
|
128
|
+
await handler() # gets the override instead of the real dependency
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
A key can be the dependency itself, or the annotation you wrote in the signature — `Dep[Session]` and `DepFactory[Session, session_dep]` both work and are normalized to the same underlying dependency:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
with push_overrides({DepFactory[Session, session_dep]: my_session}):
|
|
135
|
+
...
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Values are used as-is, but two wrappers make the intent explicit and cover the ambiguous cases:
|
|
139
|
+
|
|
140
|
+
- `ValueOverride(value)` — always inject `value`, even when it is itself callable.
|
|
141
|
+
- `FactoryOverride(factory)` — call `factory` to produce the value. Sync, async, and generator factories are all supported, with the same teardown semantics as regular dependencies.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from fastapi_injected import FactoryOverride, ValueOverride
|
|
145
|
+
|
|
146
|
+
with push_overrides(
|
|
147
|
+
{
|
|
148
|
+
Session: ValueOverride(fake_session),
|
|
149
|
+
Repository: FactoryOverride(lambda: FakeRepository()),
|
|
150
|
+
},
|
|
151
|
+
):
|
|
152
|
+
...
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
|
|
156
|
+
|
|
157
|
+
Because the surrounding scope caches resolved dependencies, an override pushed after something has already been built would silently have no effect. To catch that, `push_overrides` raises `NonFreshScopeError` if the current scope already holds cached dependencies. Pass `require_fresh_scope=False` if you know what you are doing and want the override to apply only to what has not been resolved yet:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
async with push_inject_scope():
|
|
161
|
+
await handler() # dependencies cached here
|
|
162
|
+
|
|
163
|
+
with push_overrides({Session: fake}): # raises NonFreshScopeError
|
|
164
|
+
...
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### Inspecting annotations
|
|
168
|
+
|
|
169
|
+
A few helpers are exported for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
|
|
170
|
+
|
|
171
|
+
- `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
|
|
172
|
+
- `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
|
|
173
|
+
- `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
|
|
174
|
+
|
|
119
175
|
### FastAPI request integration
|
|
120
176
|
|
|
121
177
|
Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Register `init_inject_scope` as a dependency:
|
|
@@ -96,6 +96,61 @@ async with push_inject_scope():
|
|
|
96
96
|
|
|
97
97
|
Use `@inject(new_scope=True)` to opt a function out of the surrounding scope and always get fresh dependencies.
|
|
98
98
|
|
|
99
|
+
### Overriding dependencies
|
|
100
|
+
|
|
101
|
+
`push_overrides` swaps dependencies out for the duration of a `with` block — handy in tests, or anywhere you need to run the same code against a different implementation:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from fastapi_injected import push_overrides
|
|
105
|
+
|
|
106
|
+
with push_overrides({Session: Session(closed=True)}):
|
|
107
|
+
await handler() # gets the override instead of the real dependency
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
A key can be the dependency itself, or the annotation you wrote in the signature — `Dep[Session]` and `DepFactory[Session, session_dep]` both work and are normalized to the same underlying dependency:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
with push_overrides({DepFactory[Session, session_dep]: my_session}):
|
|
114
|
+
...
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Values are used as-is, but two wrappers make the intent explicit and cover the ambiguous cases:
|
|
118
|
+
|
|
119
|
+
- `ValueOverride(value)` — always inject `value`, even when it is itself callable.
|
|
120
|
+
- `FactoryOverride(factory)` — call `factory` to produce the value. Sync, async, and generator factories are all supported, with the same teardown semantics as regular dependencies.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from fastapi_injected import FactoryOverride, ValueOverride
|
|
124
|
+
|
|
125
|
+
with push_overrides(
|
|
126
|
+
{
|
|
127
|
+
Session: ValueOverride(fake_session),
|
|
128
|
+
Repository: FactoryOverride(lambda: FakeRepository()),
|
|
129
|
+
},
|
|
130
|
+
):
|
|
131
|
+
...
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
|
|
135
|
+
|
|
136
|
+
Because the surrounding scope caches resolved dependencies, an override pushed after something has already been built would silently have no effect. To catch that, `push_overrides` raises `NonFreshScopeError` if the current scope already holds cached dependencies. Pass `require_fresh_scope=False` if you know what you are doing and want the override to apply only to what has not been resolved yet:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
async with push_inject_scope():
|
|
140
|
+
await handler() # dependencies cached here
|
|
141
|
+
|
|
142
|
+
with push_overrides({Session: fake}): # raises NonFreshScopeError
|
|
143
|
+
...
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Inspecting annotations
|
|
147
|
+
|
|
148
|
+
A few helpers are exported for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
|
|
149
|
+
|
|
150
|
+
- `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
|
|
151
|
+
- `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
|
|
152
|
+
- `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
|
|
153
|
+
|
|
99
154
|
### FastAPI request integration
|
|
100
155
|
|
|
101
156
|
Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Register `init_inject_scope` as a dependency:
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
from ._deps_tp import is_dep, unwrap_dep_dependency, unwrap_dep_tp
|
|
1
2
|
from ._fastapi_lifecycle import init_inject_scope
|
|
2
3
|
from .inject import inject
|
|
4
|
+
from .overrides import FactoryOverride, ValueOverride, push_overrides
|
|
3
5
|
from .resolve import resolve
|
|
4
6
|
from .scope import push_inject_scope
|
|
5
7
|
from .types import Dep, DepFactory, Injected
|
|
@@ -7,9 +9,15 @@ from .types import Dep, DepFactory, Injected
|
|
|
7
9
|
__all__ = [
|
|
8
10
|
"Dep",
|
|
9
11
|
"DepFactory",
|
|
12
|
+
"FactoryOverride",
|
|
10
13
|
"Injected",
|
|
14
|
+
"ValueOverride",
|
|
11
15
|
"init_inject_scope",
|
|
12
16
|
"inject",
|
|
17
|
+
"is_dep",
|
|
13
18
|
"push_inject_scope",
|
|
19
|
+
"push_overrides",
|
|
14
20
|
"resolve",
|
|
21
|
+
"unwrap_dep_dependency",
|
|
22
|
+
"unwrap_dep_tp",
|
|
15
23
|
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from typing import Annotated, Any, TypeVar, get_args, get_origin
|
|
2
|
+
|
|
3
|
+
from fastapi.params import Depends
|
|
4
|
+
from typing_inspection.typing_objects import is_typealiastype
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def unwrap_tp(tp: Any) -> Any:
|
|
8
|
+
# PEP 695 aliases can be nested, e.g. `type A = B` where `type B = Annotated[...]`
|
|
9
|
+
while is_typealiastype(tp):
|
|
10
|
+
tp = tp.__value__
|
|
11
|
+
|
|
12
|
+
return tp
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _get_annotated_metadata(tp: Any) -> tuple[Any, ...]:
|
|
16
|
+
if get_origin(tp) is Annotated:
|
|
17
|
+
return get_args(tp)[1:]
|
|
18
|
+
|
|
19
|
+
return ()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def is_dep(tp: Any) -> bool:
|
|
23
|
+
tp = unwrap_tp(tp)
|
|
24
|
+
|
|
25
|
+
return any(isinstance(tp, Depends) for tp in _get_annotated_metadata(tp))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _enforce_dep(tp: Any) -> Any:
|
|
29
|
+
tp = unwrap_tp(tp)
|
|
30
|
+
|
|
31
|
+
if not is_dep(tp):
|
|
32
|
+
msg = f"Expected a Dep, got {tp!r}"
|
|
33
|
+
raise TypeError(msg)
|
|
34
|
+
|
|
35
|
+
return tp
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def unwrap_dep_tp(obj: Any, /) -> Any:
|
|
39
|
+
obj = _enforce_dep(obj)
|
|
40
|
+
|
|
41
|
+
match get_args(obj)[0]:
|
|
42
|
+
case TypeVar(): # bare `Dep`, used without a type argument
|
|
43
|
+
return Any
|
|
44
|
+
case tp:
|
|
45
|
+
return tp
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def unwrap_dep_dependency(obj: Any, /) -> Any:
|
|
49
|
+
obj = _enforce_dep(obj)
|
|
50
|
+
tp, *metadatas = get_args(obj)
|
|
51
|
+
for metadata in metadatas:
|
|
52
|
+
if isinstance(metadata, Depends) and metadata.dependency is not None:
|
|
53
|
+
return metadata.dependency
|
|
54
|
+
|
|
55
|
+
return tp
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"is_dep",
|
|
60
|
+
"unwrap_dep_dependency",
|
|
61
|
+
"unwrap_dep_tp",
|
|
62
|
+
"unwrap_tp",
|
|
63
|
+
]
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
from collections.abc import
|
|
1
|
+
from collections.abc import AsyncGenerator
|
|
2
2
|
from functools import wraps
|
|
3
3
|
from typing import TYPE_CHECKING, Any
|
|
4
4
|
|
|
5
|
-
from fastapi import Request, WebSocket, routing
|
|
5
|
+
from fastapi import Depends, FastAPI, Request, WebSocket, routing
|
|
6
6
|
from fastapi.dependencies import utils
|
|
7
7
|
|
|
8
|
+
from .overrides import push_overrides
|
|
8
9
|
from .scope import push_inject_scope
|
|
9
10
|
from .types import DependencyCache
|
|
10
11
|
|
|
@@ -49,14 +50,27 @@ def _get_dependency_cache(request: Request) -> DependencyCache:
|
|
|
49
50
|
raise MissingDependencyCacheError("Dependency cache not found") from None
|
|
50
51
|
|
|
51
52
|
|
|
52
|
-
async def init_inject_scope(request: Request) ->
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
async def init_inject_scope(request: Request) -> AsyncGenerator[None]:
|
|
54
|
+
with push_overrides(provider=request.scope["route"].dependency_overrides_provider):
|
|
55
|
+
async with push_inject_scope(
|
|
56
|
+
dependency_cache=_get_dependency_cache(request),
|
|
57
|
+
request=request,
|
|
58
|
+
):
|
|
59
|
+
yield
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def add_injected_scope(
|
|
63
|
+
app: FastAPI,
|
|
64
|
+
/,
|
|
65
|
+
) -> None:
|
|
66
|
+
if any(dep.dependency is init_inject_scope for dep in app.router.dependencies):
|
|
67
|
+
return
|
|
68
|
+
|
|
69
|
+
dependency = Depends(init_inject_scope)
|
|
70
|
+
app.router.dependencies.insert(0, dependency)
|
|
58
71
|
|
|
59
72
|
|
|
60
73
|
__all__ = [
|
|
74
|
+
"add_injected_scope",
|
|
61
75
|
"init_inject_scope",
|
|
62
76
|
]
|
|
@@ -1,20 +1,30 @@
|
|
|
1
1
|
import inspect
|
|
2
|
-
from collections.abc import Callable
|
|
3
|
-
from contextlib import AsyncExitStack
|
|
4
|
-
from contextvars import ContextVar
|
|
2
|
+
from collections.abc import Callable, Iterator
|
|
3
|
+
from contextlib import AbstractContextManager, AsyncExitStack, contextmanager
|
|
4
|
+
from contextvars import ContextVar, Token
|
|
5
5
|
from copy import copy
|
|
6
6
|
from functools import lru_cache, wraps
|
|
7
|
-
from typing import Annotated, Any, Literal, cast, overload
|
|
7
|
+
from typing import Annotated, Any, Literal, Protocol, cast, overload, runtime_checkable
|
|
8
8
|
|
|
9
|
-
from fastapi import Depends
|
|
9
|
+
from fastapi import Depends, params
|
|
10
10
|
from fastapi.dependencies.models import Dependant
|
|
11
11
|
from fastapi.dependencies.utils import get_dependant, get_typed_signature, solve_dependencies
|
|
12
12
|
|
|
13
|
+
from ._deps_tp import is_dep, unwrap_tp
|
|
13
14
|
from .scope import InjectScope
|
|
14
15
|
from .sign import prepare_sign, update_func_sign
|
|
15
16
|
from .types import Coro, HasSignature
|
|
16
17
|
|
|
17
18
|
|
|
19
|
+
@runtime_checkable
|
|
20
|
+
class HasDependsHook[**P, R](Protocol):
|
|
21
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Any:
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
def __get_depends__(self) -> params.Depends:
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
18
28
|
@lru_cache(maxsize=1024)
|
|
19
29
|
def create_dependant[**P, R](func: Callable[P, Coro[R]], /) -> Dependant:
|
|
20
30
|
@wraps(func)
|
|
@@ -33,23 +43,36 @@ def create_dependant[**P, R](func: Callable[P, Coro[R]], /) -> Dependant:
|
|
|
33
43
|
|
|
34
44
|
|
|
35
45
|
@lru_cache(maxsize=1024)
|
|
36
|
-
def create_single_dependant[**P, R](
|
|
46
|
+
def create_single_dependant[**P, R](
|
|
47
|
+
func: Callable[P, R] | HasDependsHook[P, R],
|
|
48
|
+
/,
|
|
49
|
+
*,
|
|
50
|
+
path: str | None = None,
|
|
51
|
+
) -> Dependant:
|
|
37
52
|
async def _factory(__value__: R) -> R:
|
|
38
53
|
return __value__
|
|
39
54
|
|
|
55
|
+
match func:
|
|
56
|
+
case _ if is_dep(func):
|
|
57
|
+
annotation = unwrap_tp(func)
|
|
58
|
+
case HasDependsHook():
|
|
59
|
+
annotation = Annotated[Any, func.__get_depends__()]
|
|
60
|
+
case _:
|
|
61
|
+
annotation = Annotated[Any, Depends(func)]
|
|
62
|
+
|
|
40
63
|
cast("HasSignature", _factory).__signature__ = inspect.Signature(
|
|
41
64
|
parameters=[
|
|
42
65
|
inspect.Parameter(
|
|
43
66
|
"__value__",
|
|
44
67
|
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
45
|
-
annotation=
|
|
68
|
+
annotation=annotation,
|
|
46
69
|
),
|
|
47
70
|
],
|
|
48
71
|
return_annotation=Any,
|
|
49
72
|
)
|
|
50
73
|
|
|
51
74
|
return get_dependant(
|
|
52
|
-
path="",
|
|
75
|
+
path=path or "",
|
|
53
76
|
call=_factory,
|
|
54
77
|
)
|
|
55
78
|
|
|
@@ -82,7 +105,7 @@ async def resolve_dependencies(
|
|
|
82
105
|
request=scope.request,
|
|
83
106
|
dependant=dependant,
|
|
84
107
|
dependency_cache=copy(scope.dependency_cache),
|
|
85
|
-
dependency_overrides_provider=
|
|
108
|
+
dependency_overrides_provider=get_inject_dependency_override_provider(),
|
|
86
109
|
# this parameter is deprecated and not used
|
|
87
110
|
async_exit_stack=cast(AsyncExitStack, None),
|
|
88
111
|
embed_body_fields=False,
|
|
@@ -108,12 +131,27 @@ _dependency_override_provider: ContextVar[Any] = ContextVar(
|
|
|
108
131
|
)
|
|
109
132
|
|
|
110
133
|
|
|
111
|
-
|
|
112
|
-
|
|
134
|
+
@contextmanager
|
|
135
|
+
def _reset_token(var: ContextVar[Any], token: Token[Any]) -> Iterator[None]:
|
|
136
|
+
try:
|
|
137
|
+
yield
|
|
138
|
+
finally:
|
|
139
|
+
var.reset(token)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def set_inject_dependency_override_provider(provider: Any, /) -> AbstractContextManager[None]:
|
|
143
|
+
token = _dependency_override_provider.set(provider)
|
|
144
|
+
|
|
145
|
+
return _reset_token(_dependency_override_provider, token)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def get_inject_dependency_override_provider() -> Any | None:
|
|
149
|
+
return _dependency_override_provider.get()
|
|
113
150
|
|
|
114
151
|
|
|
115
152
|
__all__ = [
|
|
116
153
|
"create_dependant",
|
|
154
|
+
"get_inject_dependency_override_provider",
|
|
117
155
|
"resolve_dependencies",
|
|
118
156
|
"set_inject_dependency_override_provider",
|
|
119
157
|
]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from collections import ChainMap
|
|
2
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Iterator, Mapping
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ._deps_tp import is_dep, unwrap_dep_dependency
|
|
8
|
+
from .deps import get_inject_dependency_override_provider, set_inject_dependency_override_provider
|
|
9
|
+
from .scope import current_inject_scope
|
|
10
|
+
from .types import HasDependencyOverrides
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NonFreshScopeError(Exception):
|
|
14
|
+
def __init__(self) -> None:
|
|
15
|
+
super().__init__("push_overrides requires a fresh scope")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_overrides(obj: Any | None, /) -> Iterator[Mapping[Any, Any]]:
|
|
19
|
+
if obj is None:
|
|
20
|
+
return
|
|
21
|
+
|
|
22
|
+
if isinstance(obj, HasDependencyOverrides):
|
|
23
|
+
yield obj.dependency_overrides
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _get_override_key(tp: Any) -> Any:
|
|
27
|
+
if is_dep(tp):
|
|
28
|
+
value = unwrap_dep_dependency(tp)
|
|
29
|
+
|
|
30
|
+
if value is not None:
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
return tp
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class OverridesProvider:
|
|
38
|
+
dependency_overrides: Mapping[Any, Any]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _create_async_resolver[T](val: T) -> Callable[[], Awaitable[T]]:
|
|
42
|
+
async def _resolver() -> T:
|
|
43
|
+
return val
|
|
44
|
+
|
|
45
|
+
return _resolver
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _create_resolver[T](val: T, /) -> Any:
|
|
49
|
+
match val:
|
|
50
|
+
case ValueOverride(value):
|
|
51
|
+
return _create_async_resolver(value)
|
|
52
|
+
case FactoryOverride(factory):
|
|
53
|
+
return factory
|
|
54
|
+
case _:
|
|
55
|
+
return _create_async_resolver(val)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class ValueOverride[T]:
|
|
60
|
+
value: T
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class FactoryOverride[**P, T]:
|
|
65
|
+
factory: Callable[P, T | Awaitable[T] | Generator[T] | AsyncGenerator[T]]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
type Overrides = dict[Any, Any | ValueOverride | FactoryOverride]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _enforce_fresh_scope() -> None:
|
|
72
|
+
scope = current_inject_scope()
|
|
73
|
+
|
|
74
|
+
if scope is None:
|
|
75
|
+
return
|
|
76
|
+
|
|
77
|
+
if scope.dependency_cache:
|
|
78
|
+
raise NonFreshScopeError
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def create_fallback_override_provider(
|
|
82
|
+
*,
|
|
83
|
+
overrides: Overrides | None = None,
|
|
84
|
+
provider: HasDependencyOverrides | None = None,
|
|
85
|
+
) -> OverridesProvider:
|
|
86
|
+
return OverridesProvider(
|
|
87
|
+
ChainMap(
|
|
88
|
+
{_get_override_key(k): _create_resolver(v) for k, v in (overrides or {}).items()},
|
|
89
|
+
*_get_overrides(provider), # type: ignore[ty:invalid-argument-type]
|
|
90
|
+
*_get_overrides(get_inject_dependency_override_provider()), # type: ignore[ty:invalid-argument-type]
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@contextmanager
|
|
96
|
+
def push_overrides(
|
|
97
|
+
overrides: Overrides | None = None,
|
|
98
|
+
/,
|
|
99
|
+
*,
|
|
100
|
+
provider: HasDependencyOverrides | None = None,
|
|
101
|
+
require_fresh_scope: bool = True,
|
|
102
|
+
) -> Iterator[None]:
|
|
103
|
+
|
|
104
|
+
if require_fresh_scope:
|
|
105
|
+
_enforce_fresh_scope()
|
|
106
|
+
|
|
107
|
+
with set_inject_dependency_override_provider(
|
|
108
|
+
create_fallback_override_provider(
|
|
109
|
+
overrides=overrides,
|
|
110
|
+
provider=provider,
|
|
111
|
+
),
|
|
112
|
+
):
|
|
113
|
+
yield
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
__all__ = [
|
|
117
|
+
"FactoryOverride",
|
|
118
|
+
"OverridesProvider",
|
|
119
|
+
"ValueOverride",
|
|
120
|
+
"create_fallback_override_provider",
|
|
121
|
+
"push_overrides",
|
|
122
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from typing import Any, overload
|
|
3
|
+
|
|
4
|
+
from typing_extensions import TypeForm
|
|
5
|
+
|
|
6
|
+
from fastapi_injected.types import DepReturn
|
|
7
|
+
|
|
8
|
+
from .deps import HasDependsHook, create_single_dependant, resolve_dependencies
|
|
9
|
+
from .scope import inside_inject_scope
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@overload
|
|
13
|
+
async def resolve[**P, R](
|
|
14
|
+
tp: Callable[P, DepReturn[R]] | HasDependsHook[P, DepReturn[R]],
|
|
15
|
+
/,
|
|
16
|
+
*,
|
|
17
|
+
new_scope: bool = False,
|
|
18
|
+
) -> R:
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@overload
|
|
23
|
+
async def resolve[R](
|
|
24
|
+
tp: TypeForm[R],
|
|
25
|
+
/,
|
|
26
|
+
*,
|
|
27
|
+
new_scope: bool = False,
|
|
28
|
+
) -> R:
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def resolve(
|
|
33
|
+
tp: Any,
|
|
34
|
+
/,
|
|
35
|
+
*,
|
|
36
|
+
new_scope: bool = False,
|
|
37
|
+
) -> Any:
|
|
38
|
+
|
|
39
|
+
async with inside_inject_scope(
|
|
40
|
+
new_scope=new_scope,
|
|
41
|
+
) as inject_scope:
|
|
42
|
+
dependant = create_single_dependant(
|
|
43
|
+
tp,
|
|
44
|
+
path=inject_scope.path_format,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
return await resolve_dependencies(
|
|
48
|
+
dependant,
|
|
49
|
+
inject_scope,
|
|
50
|
+
single=True,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"resolve",
|
|
56
|
+
]
|
|
@@ -7,6 +7,7 @@ from contextvars import ContextVar
|
|
|
7
7
|
from dataclasses import dataclass
|
|
8
8
|
|
|
9
9
|
from fastapi import Request
|
|
10
|
+
from fastapi.routing import APIRoute, APIWebSocketRoute
|
|
10
11
|
from starlette.types import Message, Scope
|
|
11
12
|
|
|
12
13
|
from .types import DependencyCache
|
|
@@ -50,6 +51,14 @@ class InjectScope:
|
|
|
50
51
|
dependency_cache: DependencyCache
|
|
51
52
|
request: Request
|
|
52
53
|
|
|
54
|
+
@property
|
|
55
|
+
def path_format(self) -> str | None:
|
|
56
|
+
match self.request.scope:
|
|
57
|
+
case {"route": APIRoute() | APIWebSocketRoute() as route}:
|
|
58
|
+
return route.path_format
|
|
59
|
+
case _:
|
|
60
|
+
return None
|
|
61
|
+
|
|
53
62
|
|
|
54
63
|
_inject_scope: ContextVar[InjectScope | None] = ContextVar(
|
|
55
64
|
"_inject_scope",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import inspect
|
|
2
|
-
from collections.abc import Callable, Coroutine
|
|
3
|
-
from typing import TYPE_CHECKING, Annotated, Any, Protocol, TypeVar
|
|
2
|
+
from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Mapping
|
|
3
|
+
from typing import TYPE_CHECKING, Annotated, Any, Protocol, TypeVar, runtime_checkable
|
|
4
4
|
|
|
5
5
|
from fastapi import Depends
|
|
6
6
|
from fastapi.types import DependencyCacheKey
|
|
@@ -49,14 +49,23 @@ class HasSignature(Protocol):
|
|
|
49
49
|
__signature__: inspect.Signature
|
|
50
50
|
|
|
51
51
|
|
|
52
|
+
@runtime_checkable
|
|
53
|
+
class HasDependencyOverrides(Protocol):
|
|
54
|
+
dependency_overrides: Mapping[Any, Any]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
type DepReturn[R] = Coro[R] | Iterator[R] | AsyncIterator[R] | R
|
|
58
|
+
|
|
52
59
|
__all__ = [
|
|
53
60
|
"AsyncFunc",
|
|
54
61
|
"Coro",
|
|
55
62
|
"Decorator",
|
|
56
63
|
"Dep",
|
|
57
64
|
"DepFactory",
|
|
65
|
+
"DepReturn",
|
|
58
66
|
"DependencyCache",
|
|
59
67
|
"Func",
|
|
68
|
+
"HasDependencyOverrides",
|
|
60
69
|
"HasSignature",
|
|
61
70
|
"Injected",
|
|
62
71
|
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "fastapi-injected"
|
|
3
|
-
version = "0.1
|
|
3
|
+
version = "0.2.1"
|
|
4
4
|
description = "Yet another library to reuse fastapi dependency injection"
|
|
5
5
|
authors = [
|
|
6
6
|
{ name = "Yurii Karabas", email = "1998uriyyo@gmail.com" },
|
|
@@ -20,6 +20,7 @@ classifiers = [
|
|
|
20
20
|
dependencies = [
|
|
21
21
|
"fastapi>=0.139.2",
|
|
22
22
|
"typing-extensions>=4.16.0",
|
|
23
|
+
"typing-inspection>=0.4.4",
|
|
23
24
|
]
|
|
24
25
|
|
|
25
26
|
[dependency-groups]
|
|
@@ -65,6 +66,7 @@ ignore = [
|
|
|
65
66
|
"FBT", # ignore flake8-boolean-trap
|
|
66
67
|
"EM", # ignore error message formatting
|
|
67
68
|
"TC", # ignore type checking
|
|
69
|
+
"CPY", # ignore copyright
|
|
68
70
|
]
|
|
69
71
|
exclude = [
|
|
70
72
|
".bzr",
|
|
@@ -28,9 +28,19 @@ class Container:
|
|
|
28
28
|
ctx: DepFactory[ContextState, ctx_dep]
|
|
29
29
|
|
|
30
30
|
|
|
31
|
+
def get_value() -> int:
|
|
32
|
+
return 1
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class State:
|
|
37
|
+
value: DepFactory[int, get_value]
|
|
38
|
+
|
|
39
|
+
|
|
31
40
|
__all__ = [
|
|
32
41
|
"Child",
|
|
33
42
|
"Container",
|
|
34
43
|
"ContextState",
|
|
44
|
+
"State",
|
|
35
45
|
"ctx_dep",
|
|
36
46
|
]
|