fastapi-injected 0.1.3__tar.gz → 0.2.0__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.2.0/PKG-INFO +195 -0
- fastapi_injected-0.2.0/README.md +175 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/__init__.py +8 -0
- fastapi_injected-0.2.0/fastapi_injected/_deps_tp.py +60 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/deps.py +26 -12
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/inject.py +2 -2
- fastapi_injected-0.2.0/fastapi_injected/overrides.py +106 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/resolve.py +2 -2
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/scope.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/types.py +8 -2
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/pyproject.toml +3 -1
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/deps.py +10 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/uv.lock +71 -69
- fastapi_injected-0.1.3/PKG-INFO +0 -118
- fastapi_injected-0.1.3/README.md +0 -99
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.github/dependabot.yml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.github/workflows/automerge.yml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.github/workflows/lint.yml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.github/workflows/publish.yml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.github/workflows/test.yml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.gitignore +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/.pre-commit-config.yaml +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/LICENSE +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/_fastapi_lifecycle.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/fastapi_injected/sign.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/__init__.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/ext/__init__.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/ext/test_pydantic_ai.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/test_fastapi.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/test_inject.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/test_resolve.py +0 -0
- {fastapi_injected-0.1.3 → fastapi_injected-0.2.0}/tests/test_typing.py +0 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-injected
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Yet another library to reuse fastapi dependency injection
|
|
5
|
+
Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
|
|
6
|
+
Author-email: Yurii Karabas <1998uriyyo@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Requires-Dist: fastapi>=0.139.2
|
|
18
|
+
Requires-Dist: typing-extensions>=4.16.0
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# fastapi-injected
|
|
22
|
+
|
|
23
|
+
Yet another attempt to reuse FastAPI's dependency injection outside of request handlers.
|
|
24
|
+
|
|
25
|
+
This is an opinionated library: it takes the DI machinery you already know from FastAPI (`Depends`, generator dependencies with teardown, dependency caching) and makes it usable in plain async functions — background jobs, CLI commands, workers, scripts — without a `Request` in sight.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install fastapi-injected
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Requires Python 3.12+.
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Declare dependencies as regular classes and annotate fields with `Dep[...]`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
from typing import AsyncIterator
|
|
42
|
+
|
|
43
|
+
from fastapi_injected import Dep, DepFactory, Injected, inject
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Session:
|
|
48
|
+
closed: bool = False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def session_dep() -> AsyncIterator[Session]:
|
|
52
|
+
session = Session()
|
|
53
|
+
try:
|
|
54
|
+
yield session
|
|
55
|
+
finally:
|
|
56
|
+
session.closed = True
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Repository:
|
|
61
|
+
session: DepFactory[Session, session_dep]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Service:
|
|
66
|
+
repo: Dep[Repository]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@inject
|
|
70
|
+
async def handler(*, service: Dep[Service] = Injected) -> None:
|
|
71
|
+
... # service is built and injected, session is closed on exit
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
await handler()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- `Dep[T]` — resolve `T` by calling it, same as FastAPI's `Annotated[T, Depends()]`.
|
|
78
|
+
- `DepFactory[T, factory]` — resolve `T` via a factory, same as `Annotated[T, Depends(factory)]`. Generator factories get proper teardown.
|
|
79
|
+
- `Injected` — a sentinel default that exists purely to make type checkers happy: without it they would complain about a missing argument at call sites. At runtime the parameter is always filled in by `@inject`.
|
|
80
|
+
|
|
81
|
+
Injected parameters mix freely with regular ones — pass your own arguments as usual and the rest is injected:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
@inject
|
|
85
|
+
async def add(a: int, b: int, *, service: Dep[Service] = Injected) -> int:
|
|
86
|
+
...
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
result = await add(1, 2)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Resolving a type directly
|
|
93
|
+
|
|
94
|
+
No decorator needed — resolve a dependency graph on demand:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from fastapi_injected import resolve
|
|
98
|
+
|
|
99
|
+
service = await resolve(Service)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Like `@inject`, `resolve` accepts `new_scope=True` to force a fresh scope instead of reusing the surrounding one.
|
|
103
|
+
|
|
104
|
+
### Scopes and caching
|
|
105
|
+
|
|
106
|
+
By default every call to an injected function gets its own scope: dependencies are built, cached within the call, and torn down when it returns. Wrap several calls in `push_inject_scope()` to share one cache (and defer teardown to the end of the scope):
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from fastapi_injected import push_inject_scope
|
|
110
|
+
|
|
111
|
+
async with push_inject_scope():
|
|
112
|
+
a = await handler() # dependencies built here
|
|
113
|
+
b = await handler() # same instances reused
|
|
114
|
+
# generator dependencies are torn down here
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Use `@inject(new_scope=True)` to opt a function out of the surrounding scope and always get fresh dependencies.
|
|
118
|
+
|
|
119
|
+
### Overriding dependencies
|
|
120
|
+
|
|
121
|
+
`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:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from fastapi_injected import push_overrides
|
|
125
|
+
|
|
126
|
+
with push_overrides({Session: Session(closed=True)}):
|
|
127
|
+
await handler() # gets the override instead of the real dependency
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
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:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
with push_overrides({DepFactory[Session, session_dep]: my_session}):
|
|
134
|
+
...
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Values are used as-is, but two wrappers make the intent explicit and cover the ambiguous cases:
|
|
138
|
+
|
|
139
|
+
- `ValueOverride(value)` — always inject `value`, even when it is itself callable.
|
|
140
|
+
- `FactoryOverride(factory)` — call `factory` to produce the value. Sync, async, and generator factories are all supported, with the same teardown semantics as regular dependencies.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from fastapi_injected import FactoryOverride, ValueOverride
|
|
144
|
+
|
|
145
|
+
with push_overrides(
|
|
146
|
+
{
|
|
147
|
+
Session: ValueOverride(fake_session),
|
|
148
|
+
Repository: FactoryOverride(lambda: FakeRepository()),
|
|
149
|
+
},
|
|
150
|
+
):
|
|
151
|
+
...
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
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:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
async with push_inject_scope():
|
|
160
|
+
await handler() # dependencies cached here
|
|
161
|
+
|
|
162
|
+
with push_overrides({Session: fake}): # raises NonFreshScopeError
|
|
163
|
+
...
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Inspecting annotations
|
|
167
|
+
|
|
168
|
+
A few helpers are exported for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
|
|
169
|
+
|
|
170
|
+
- `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
|
|
171
|
+
- `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
|
|
172
|
+
- `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
|
|
173
|
+
|
|
174
|
+
### FastAPI request integration
|
|
175
|
+
|
|
176
|
+
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:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
from fastapi import Depends, FastAPI
|
|
180
|
+
from fastapi_injected import Dep, init_inject_scope, resolve
|
|
181
|
+
|
|
182
|
+
app = FastAPI(dependencies=[Depends(init_inject_scope)])
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@app.get("/")
|
|
186
|
+
async def route(service: Dep[Service]) -> str:
|
|
187
|
+
same = await resolve(Service) # same instance as `service`
|
|
188
|
+
...
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
MIT
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# fastapi-injected
|
|
2
|
+
|
|
3
|
+
Yet another attempt to reuse FastAPI's dependency injection outside of request handlers.
|
|
4
|
+
|
|
5
|
+
This is an opinionated library: it takes the DI machinery you already know from FastAPI (`Depends`, generator dependencies with teardown, dependency caching) and makes it usable in plain async functions — background jobs, CLI commands, workers, scripts — without a `Request` in sight.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install fastapi-injected
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Python 3.12+.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
Declare dependencies as regular classes and annotate fields with `Dep[...]`:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import AsyncIterator
|
|
22
|
+
|
|
23
|
+
from fastapi_injected import Dep, DepFactory, Injected, inject
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Session:
|
|
28
|
+
closed: bool = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def session_dep() -> AsyncIterator[Session]:
|
|
32
|
+
session = Session()
|
|
33
|
+
try:
|
|
34
|
+
yield session
|
|
35
|
+
finally:
|
|
36
|
+
session.closed = True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Repository:
|
|
41
|
+
session: DepFactory[Session, session_dep]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Service:
|
|
46
|
+
repo: Dep[Repository]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@inject
|
|
50
|
+
async def handler(*, service: Dep[Service] = Injected) -> None:
|
|
51
|
+
... # service is built and injected, session is closed on exit
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
await handler()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- `Dep[T]` — resolve `T` by calling it, same as FastAPI's `Annotated[T, Depends()]`.
|
|
58
|
+
- `DepFactory[T, factory]` — resolve `T` via a factory, same as `Annotated[T, Depends(factory)]`. Generator factories get proper teardown.
|
|
59
|
+
- `Injected` — a sentinel default that exists purely to make type checkers happy: without it they would complain about a missing argument at call sites. At runtime the parameter is always filled in by `@inject`.
|
|
60
|
+
|
|
61
|
+
Injected parameters mix freely with regular ones — pass your own arguments as usual and the rest is injected:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
@inject
|
|
65
|
+
async def add(a: int, b: int, *, service: Dep[Service] = Injected) -> int:
|
|
66
|
+
...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
result = await add(1, 2)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Resolving a type directly
|
|
73
|
+
|
|
74
|
+
No decorator needed — resolve a dependency graph on demand:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from fastapi_injected import resolve
|
|
78
|
+
|
|
79
|
+
service = await resolve(Service)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Like `@inject`, `resolve` accepts `new_scope=True` to force a fresh scope instead of reusing the surrounding one.
|
|
83
|
+
|
|
84
|
+
### Scopes and caching
|
|
85
|
+
|
|
86
|
+
By default every call to an injected function gets its own scope: dependencies are built, cached within the call, and torn down when it returns. Wrap several calls in `push_inject_scope()` to share one cache (and defer teardown to the end of the scope):
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from fastapi_injected import push_inject_scope
|
|
90
|
+
|
|
91
|
+
async with push_inject_scope():
|
|
92
|
+
a = await handler() # dependencies built here
|
|
93
|
+
b = await handler() # same instances reused
|
|
94
|
+
# generator dependencies are torn down here
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Use `@inject(new_scope=True)` to opt a function out of the surrounding scope and always get fresh dependencies.
|
|
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
|
+
|
|
154
|
+
### FastAPI request integration
|
|
155
|
+
|
|
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:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from fastapi import Depends, FastAPI
|
|
160
|
+
from fastapi_injected import Dep, init_inject_scope, resolve
|
|
161
|
+
|
|
162
|
+
app = FastAPI(dependencies=[Depends(init_inject_scope)])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@app.get("/")
|
|
166
|
+
async def route(service: Dep[Service]) -> str:
|
|
167
|
+
same = await resolve(Service) # same instance as `service`
|
|
168
|
+
...
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request.
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
|
@@ -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,60 @@
|
|
|
1
|
+
from typing import Annotated, Any, TypeAliasType, TypeVar, get_args, get_origin
|
|
2
|
+
|
|
3
|
+
from fastapi.params import Depends
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _unwrap_tp(tp: Any) -> Any:
|
|
7
|
+
if isinstance(tp, TypeAliasType):
|
|
8
|
+
return tp.__value__
|
|
9
|
+
|
|
10
|
+
return tp
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _get_annotated_metadata(tp: Any) -> tuple[Any, ...]:
|
|
14
|
+
if get_origin(tp) is Annotated:
|
|
15
|
+
return get_args(tp)[1:]
|
|
16
|
+
|
|
17
|
+
return ()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_dep(tp: Any) -> bool:
|
|
21
|
+
tp = _unwrap_tp(tp)
|
|
22
|
+
|
|
23
|
+
return any(isinstance(tp, Depends) for tp in _get_annotated_metadata(tp))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _enforce_dep(tp: Any) -> Any:
|
|
27
|
+
tp = _unwrap_tp(tp)
|
|
28
|
+
|
|
29
|
+
if not is_dep(tp):
|
|
30
|
+
msg = f"Expected a Dep, got {tp!r}"
|
|
31
|
+
raise TypeError(msg)
|
|
32
|
+
|
|
33
|
+
return tp
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def unwrap_dep_tp(obj: Any, /) -> Any:
|
|
37
|
+
obj = _enforce_dep(obj)
|
|
38
|
+
|
|
39
|
+
match get_args(obj)[0]:
|
|
40
|
+
case TypeVar(): # bare `Dep`, used without a type argument
|
|
41
|
+
return Any
|
|
42
|
+
case tp:
|
|
43
|
+
return tp
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def unwrap_dep_dependency(obj: Any, /) -> Any:
|
|
47
|
+
obj = _enforce_dep(obj)
|
|
48
|
+
tp, *metadatas = get_args(obj)
|
|
49
|
+
for metadata in metadatas:
|
|
50
|
+
if isinstance(metadata, Depends) and metadata.dependency is not None:
|
|
51
|
+
return metadata.dependency
|
|
52
|
+
|
|
53
|
+
return tp
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"is_dep",
|
|
58
|
+
"unwrap_dep_dependency",
|
|
59
|
+
"unwrap_dep_tp",
|
|
60
|
+
]
|
|
@@ -1,15 +1,14 @@
|
|
|
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
7
|
from typing import Annotated, Any, Literal, cast, overload
|
|
8
8
|
|
|
9
9
|
from fastapi import Depends
|
|
10
10
|
from fastapi.dependencies.models import Dependant
|
|
11
|
-
from fastapi.dependencies.utils import get_dependant, get_typed_signature
|
|
12
|
-
from fastapi.dependencies.utils import solve_dependencies as _solve_dependencies
|
|
11
|
+
from fastapi.dependencies.utils import get_dependant, get_typed_signature, solve_dependencies
|
|
13
12
|
|
|
14
13
|
from .scope import InjectScope
|
|
15
14
|
from .sign import prepare_sign, update_func_sign
|
|
@@ -56,7 +55,7 @@ def create_single_dependant[**P, R](func: Callable[P, R], /) -> Dependant:
|
|
|
56
55
|
|
|
57
56
|
|
|
58
57
|
@overload
|
|
59
|
-
async def
|
|
58
|
+
async def resolve_dependencies(
|
|
60
59
|
dependant: Dependant,
|
|
61
60
|
scope: InjectScope,
|
|
62
61
|
*,
|
|
@@ -65,7 +64,7 @@ async def solve_dependencies(
|
|
|
65
64
|
|
|
66
65
|
|
|
67
66
|
@overload
|
|
68
|
-
async def
|
|
67
|
+
async def resolve_dependencies(
|
|
69
68
|
dependant: Dependant,
|
|
70
69
|
scope: InjectScope,
|
|
71
70
|
*,
|
|
@@ -73,13 +72,13 @@ async def solve_dependencies(
|
|
|
73
72
|
) -> Any: ...
|
|
74
73
|
|
|
75
74
|
|
|
76
|
-
async def
|
|
75
|
+
async def resolve_dependencies(
|
|
77
76
|
dependant: Dependant,
|
|
78
77
|
scope: InjectScope,
|
|
79
78
|
*,
|
|
80
79
|
single: bool = False,
|
|
81
80
|
) -> dict[str, Any]:
|
|
82
|
-
solved = await
|
|
81
|
+
solved = await solve_dependencies(
|
|
83
82
|
request=scope.request,
|
|
84
83
|
dependant=dependant,
|
|
85
84
|
dependency_cache=copy(scope.dependency_cache),
|
|
@@ -109,12 +108,27 @@ _dependency_override_provider: ContextVar[Any] = ContextVar(
|
|
|
109
108
|
)
|
|
110
109
|
|
|
111
110
|
|
|
112
|
-
|
|
113
|
-
|
|
111
|
+
@contextmanager
|
|
112
|
+
def _reset_token(var: ContextVar[Any], token: Token[Any]) -> Iterator[None]:
|
|
113
|
+
try:
|
|
114
|
+
yield
|
|
115
|
+
finally:
|
|
116
|
+
var.reset(token)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def set_inject_dependency_override_provider(provider: Any, /) -> AbstractContextManager[None]:
|
|
120
|
+
token = _dependency_override_provider.set(provider)
|
|
121
|
+
|
|
122
|
+
return _reset_token(_dependency_override_provider, token)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def get_inject_dependency_override_provider() -> Any | None:
|
|
126
|
+
return _dependency_override_provider.get()
|
|
114
127
|
|
|
115
128
|
|
|
116
129
|
__all__ = [
|
|
117
130
|
"create_dependant",
|
|
131
|
+
"get_inject_dependency_override_provider",
|
|
132
|
+
"resolve_dependencies",
|
|
118
133
|
"set_inject_dependency_override_provider",
|
|
119
|
-
"solve_dependencies",
|
|
120
134
|
]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
from functools import partial, wraps
|
|
2
2
|
from typing import overload
|
|
3
3
|
|
|
4
|
-
from .deps import create_dependant,
|
|
4
|
+
from .deps import create_dependant, resolve_dependencies
|
|
5
5
|
from .scope import inside_inject_scope
|
|
6
6
|
from .sign import strip_sign
|
|
7
7
|
from .types import AsyncFunc, Decorator
|
|
@@ -40,7 +40,7 @@ def inject[**P, R](
|
|
|
40
40
|
async with inside_inject_scope(
|
|
41
41
|
new_scope=new_scope,
|
|
42
42
|
) as inject_scope:
|
|
43
|
-
solved = await
|
|
43
|
+
solved = await resolve_dependencies(dependant, inject_scope)
|
|
44
44
|
|
|
45
45
|
for key, value in solved.items():
|
|
46
46
|
kwargs.setdefault(key, value)
|
|
@@ -0,0 +1,106 @@
|
|
|
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_current_overrides() -> Iterator[Mapping[Any, Any]]:
|
|
19
|
+
obj = get_inject_dependency_override_provider()
|
|
20
|
+
|
|
21
|
+
if isinstance(obj, HasDependencyOverrides):
|
|
22
|
+
yield obj.dependency_overrides
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _get_override_key(tp: Any) -> Any:
|
|
26
|
+
if is_dep(tp):
|
|
27
|
+
value = unwrap_dep_dependency(tp)
|
|
28
|
+
|
|
29
|
+
if value is not None:
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
return tp
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class _OverridesProvider:
|
|
37
|
+
dependency_overrides: Mapping[Any, Any]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _create_async_resolver[T](val: T) -> Callable[[], Awaitable[T]]:
|
|
41
|
+
async def _resolver() -> T:
|
|
42
|
+
return val
|
|
43
|
+
|
|
44
|
+
return _resolver
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _create_resolver[T](val: T, /) -> Any:
|
|
48
|
+
match val:
|
|
49
|
+
case ValueOverride(value):
|
|
50
|
+
return _create_async_resolver(value)
|
|
51
|
+
case FactoryOverride(factory):
|
|
52
|
+
return factory
|
|
53
|
+
case _:
|
|
54
|
+
return _create_async_resolver(val)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class ValueOverride[T]:
|
|
59
|
+
value: T
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class FactoryOverride[**P, T]:
|
|
64
|
+
factory: Callable[P, T | Awaitable[T] | Generator[T] | AsyncGenerator[T]]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
type Overrides = dict[Any, Any | ValueOverride | FactoryOverride]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _enforce_fresh_scope() -> None:
|
|
71
|
+
scope = current_inject_scope()
|
|
72
|
+
|
|
73
|
+
if scope is None:
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
if scope.dependency_cache:
|
|
77
|
+
raise NonFreshScopeError
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@contextmanager
|
|
81
|
+
def push_overrides(
|
|
82
|
+
overrides: Overrides,
|
|
83
|
+
/,
|
|
84
|
+
*,
|
|
85
|
+
require_fresh_scope: bool = True,
|
|
86
|
+
) -> Iterator[None]:
|
|
87
|
+
|
|
88
|
+
if require_fresh_scope:
|
|
89
|
+
_enforce_fresh_scope()
|
|
90
|
+
|
|
91
|
+
deps = ChainMap(
|
|
92
|
+
{_get_override_key(k): _create_resolver(v) for k, v in overrides.items()},
|
|
93
|
+
*_get_current_overrides(), # type: ignore[ty:invalid-argument-type]
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
with set_inject_dependency_override_provider(
|
|
97
|
+
_OverridesProvider(deps),
|
|
98
|
+
):
|
|
99
|
+
yield
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
__all__ = [
|
|
103
|
+
"FactoryOverride",
|
|
104
|
+
"ValueOverride",
|
|
105
|
+
"push_overrides",
|
|
106
|
+
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from typing_extensions import TypeForm
|
|
2
2
|
|
|
3
|
-
from .deps import create_single_dependant,
|
|
3
|
+
from .deps import create_single_dependant, resolve_dependencies
|
|
4
4
|
from .scope import inside_inject_scope
|
|
5
5
|
|
|
6
6
|
|
|
@@ -14,7 +14,7 @@ async def resolve[R](
|
|
|
14
14
|
async with inside_inject_scope(
|
|
15
15
|
new_scope=new_scope,
|
|
16
16
|
) as inject_scope:
|
|
17
|
-
return await
|
|
17
|
+
return await resolve_dependencies(
|
|
18
18
|
dependant,
|
|
19
19
|
inject_scope,
|
|
20
20
|
single=True,
|
|
File without changes
|