fastapi-injected 0.4.1__tar.gz → 0.4.3__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.
Files changed (81) hide show
  1. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.github/workflows/test.yml +1 -1
  2. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/PKG-INFO +61 -6
  3. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/README.md +58 -4
  4. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/__init__.py +4 -1
  5. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_bind.py +7 -1
  6. fastapi_injected-0.4.3/fastapi_injected/_body.py +90 -0
  7. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_cache.py +1 -1
  8. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_calls.py +1 -1
  9. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_deps_tp.py +15 -1
  10. fastapi_injected-0.4.3/fastapi_injected/_not_none.py +63 -0
  11. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/ctx.py +132 -31
  12. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/deps.py +2 -1
  13. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/fastapi.py +5 -3
  14. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/inject.py +1 -1
  15. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/overrides.py +3 -5
  16. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/signature.py +6 -1
  17. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/pyproject.toml +3 -2
  18. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/bind.py +1 -1
  19. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/ctx.py +1 -1
  20. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/resolve.py +1 -1
  21. fastapi_injected-0.4.3/tests/conftest.py +12 -0
  22. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_bind.py +43 -2
  23. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_body.py +1 -12
  24. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_body_reads.py +3 -10
  25. fastapi_injected-0.4.3/tests/test_default_app.py +76 -0
  26. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_dependant_cache.py +1 -1
  27. fastapi_injected-0.4.3/tests/test_not_none.py +88 -0
  28. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_overrides.py +73 -1
  29. fastapi_injected-0.4.3/tests/test_type_checking_aliases.py +43 -0
  30. fastapi_injected-0.4.3/uv.lock +857 -0
  31. fastapi_injected-0.4.1/fastapi_injected/_body.py +0 -108
  32. fastapi_injected-0.4.1/uv.lock +0 -819
  33. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.github/dependabot.yml +0 -0
  34. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.github/workflows/automerge.yml +0 -0
  35. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.github/workflows/lint.yml +0 -0
  36. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.github/workflows/publish.yml +0 -0
  37. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.gitignore +0 -0
  38. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/.pre-commit-config.yaml +0 -0
  39. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/LICENSE +0 -0
  40. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_dataclass.py +0 -0
  41. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_given.py +0 -0
  42. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_injected.py +0 -0
  43. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_overrides.py +0 -0
  44. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/_rlock.py +0 -0
  45. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/ext.py +0 -0
  46. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/reflect/__init__.py +0 -0
  47. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_dependant.py +0 -0
  48. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_openapi.py +0 -0
  49. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_routes.py +0 -0
  50. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/resolve.py +0 -0
  51. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/fastapi_injected/types.py +0 -0
  52. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/__init__.py +0 -0
  53. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/__init__.py +0 -0
  54. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/annotations.py +0 -0
  55. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/arg.py +0 -0
  56. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/dataclass.py +0 -0
  57. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/deps.py +0 -0
  58. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/errors.py +0 -0
  59. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/given.py +0 -0
  60. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/inject.py +0 -0
  61. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/injected.py +0 -0
  62. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/integration.py +0 -0
  63. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/markers.py +0 -0
  64. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/_typing/overrides.py +0 -0
  65. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/deps.py +0 -0
  66. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/ext/__init__.py +0 -0
  67. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/ext/test_pydantic_ai.py +0 -0
  68. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_cache.py +0 -0
  69. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_calls.py +0 -0
  70. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_concurrency.py +0 -0
  71. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_ctx.py +0 -0
  72. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_dataclass.py +0 -0
  73. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_errors.py +0 -0
  74. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_fastapi.py +0 -0
  75. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_given.py +0 -0
  76. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_inject.py +0 -0
  77. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_injected.py +0 -0
  78. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_reflect.py +0 -0
  79. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_request_params.py +0 -0
  80. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_resolve.py +0 -0
  81. {fastapi_injected-0.4.1 → fastapi_injected-0.4.3}/tests/test_rlock.py +0 -0
@@ -15,7 +15,7 @@ jobs:
15
15
  strategy:
16
16
  fail-fast: false
17
17
  matrix:
18
- python-version: ["3.12", "3.13", "3.14"]
18
+ python-version: ["3.12", "3.13", "3.14", "3.15"]
19
19
 
20
20
  steps:
21
21
  - uses: actions/checkout@v7
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: fastapi-injected
3
- Version: 0.4.1
3
+ Version: 0.4.3
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>
@@ -13,8 +13,9 @@ Classifier: Programming Language :: Python :: 3 :: Only
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
15
  Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
16
17
  Requires-Python: >=3.12
17
- Requires-Dist: fastapi>=0.141.0
18
+ Requires-Dist: fastapi>=0.158.0
18
19
  Requires-Dist: typing-extensions>=4.16.0
19
20
  Requires-Dist: typing-inspection>=0.4.4
20
21
  Description-Content-Type: text/markdown
@@ -162,7 +163,7 @@ async with injection_ctx(app=app):
162
163
  await handler() # `request.app.state` resolves as it does in a route
163
164
  ```
164
165
 
165
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
166
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
166
167
 
167
168
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
168
169
 
@@ -221,7 +222,22 @@ with push_overrides(
221
222
 
222
223
  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.
223
224
 
224
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
225
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
226
+
227
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
228
+
229
+ ```python
230
+ async with injection_ctx():
231
+ async with push_overrides({Session: fake}):
232
+ await handler() # a generator dependency built here...
233
+ # ...is torn down here
234
+
235
+ with push_overrides({Session: fake}):
236
+ await handler()
237
+ # still open - torn down when `injection_ctx()` ends
238
+ ```
239
+
240
+ Reuse of the surrounding cache works the same either way:
225
241
 
226
242
  ```python
227
243
  async with injection_ctx():
@@ -245,6 +261,8 @@ async with injection_ctx({Session: fake}) as ctx:
245
261
 
246
262
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
247
263
 
264
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
265
+
248
266
  ### Dependencies that are objects
249
267
 
250
268
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -290,6 +308,28 @@ except DependencyResolutionError as exc:
290
308
 
291
309
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
292
310
 
311
+ ### Values that must be there
312
+
313
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
314
+
315
+ ```python
316
+ from typing import Annotated
317
+ from fastapi import Depends
318
+ from fastapi_injected import NotNone
319
+
320
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
321
+ type UserDep = NotNone[User, MaybeUserDep]
322
+
323
+
324
+ @app.get("/users/{user_id}")
325
+ async def get_user(user: UserDep) -> User:
326
+ return user # never None here
327
+ ```
328
+
329
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
330
+
331
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
332
+
293
333
  ### Dependencies decided at runtime
294
334
 
295
335
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -322,6 +362,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
322
362
 
323
363
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
324
364
 
365
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
366
+
325
367
  ### Dependencies as objects
326
368
 
327
369
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -413,6 +455,19 @@ async def route(service: Dep[Service]) -> str:
413
455
  ...
414
456
  ```
415
457
 
458
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
459
+
460
+ ```python
461
+ from fastapi_injected import set_default_app
462
+
463
+ set_default_app(worker_app) # for the rest of the process
464
+
465
+ with set_default_app(test_app): # only inside the block
466
+ await job()
467
+ ```
468
+
469
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
470
+
416
471
  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. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
417
472
 
418
473
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -470,8 +525,8 @@ The root package is what you need to use the library, and the surface a release
470
525
  | | |
471
526
  | --- | --- |
472
527
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
473
- | Resolving | `inject`, `resolve`, `bind_deps` |
474
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
528
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
529
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
475
530
  | FastAPI integration | `add_injection` |
476
531
  | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
477
532
 
@@ -141,7 +141,7 @@ async with injection_ctx(app=app):
141
141
  await handler() # `request.app.state` resolves as it does in a route
142
142
  ```
143
143
 
144
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
144
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
145
145
 
146
146
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
147
147
 
@@ -200,7 +200,22 @@ with push_overrides(
200
200
 
201
201
  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.
202
202
 
203
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
203
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
204
+
205
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
206
+
207
+ ```python
208
+ async with injection_ctx():
209
+ async with push_overrides({Session: fake}):
210
+ await handler() # a generator dependency built here...
211
+ # ...is torn down here
212
+
213
+ with push_overrides({Session: fake}):
214
+ await handler()
215
+ # still open - torn down when `injection_ctx()` ends
216
+ ```
217
+
218
+ Reuse of the surrounding cache works the same either way:
204
219
 
205
220
  ```python
206
221
  async with injection_ctx():
@@ -224,6 +239,8 @@ async with injection_ctx({Session: fake}) as ctx:
224
239
 
225
240
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
226
241
 
242
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
243
+
227
244
  ### Dependencies that are objects
228
245
 
229
246
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -269,6 +286,28 @@ except DependencyResolutionError as exc:
269
286
 
270
287
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
271
288
 
289
+ ### Values that must be there
290
+
291
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
292
+
293
+ ```python
294
+ from typing import Annotated
295
+ from fastapi import Depends
296
+ from fastapi_injected import NotNone
297
+
298
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
299
+ type UserDep = NotNone[User, MaybeUserDep]
300
+
301
+
302
+ @app.get("/users/{user_id}")
303
+ async def get_user(user: UserDep) -> User:
304
+ return user # never None here
305
+ ```
306
+
307
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
308
+
309
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
310
+
272
311
  ### Dependencies decided at runtime
273
312
 
274
313
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -301,6 +340,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
301
340
 
302
341
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
303
342
 
343
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
344
+
304
345
  ### Dependencies as objects
305
346
 
306
347
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -392,6 +433,19 @@ async def route(service: Dep[Service]) -> str:
392
433
  ...
393
434
  ```
394
435
 
436
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
437
+
438
+ ```python
439
+ from fastapi_injected import set_default_app
440
+
441
+ set_default_app(worker_app) # for the rest of the process
442
+
443
+ with set_default_app(test_app): # only inside the block
444
+ await job()
445
+ ```
446
+
447
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
448
+
395
449
  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. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
396
450
 
397
451
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -449,8 +503,8 @@ The root package is what you need to use the library, and the surface a release
449
503
  | | |
450
504
  | --- | --- |
451
505
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
452
- | Resolving | `inject`, `resolve`, `bind_deps` |
453
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
506
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
507
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
454
508
  | FastAPI integration | `add_injection` |
455
509
  | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
456
510
 
@@ -1,6 +1,7 @@
1
1
  from ._bind import bind_deps
2
2
  from ._given import Given
3
- from .ctx import InjectionContext, UnboundContextError, injection_ctx, synthetic_request
3
+ from ._not_none import NotNone
4
+ from .ctx import InjectionContext, UnboundContextError, injection_ctx, set_default_app, synthetic_request
4
5
  from .deps import DependencyResolutionError, UnnamedParamError
5
6
  from .fastapi import add_injection
6
7
  from .inject import inject
@@ -19,6 +20,7 @@ __all__ = [
19
20
  "Injected",
20
21
  "InjectionContext",
21
22
  "NotADependencyError",
23
+ "NotNone",
22
24
  "UnboundContextError",
23
25
  "UnnamedParamError",
24
26
  "ValueOverride",
@@ -29,5 +31,6 @@ __all__ = [
29
31
  "override_app",
30
32
  "push_overrides",
31
33
  "resolve",
34
+ "set_default_app",
32
35
  "synthetic_request",
33
36
  ]
@@ -7,6 +7,7 @@ from fastapi.params import Depends
7
7
 
8
8
  from ._calls import annotated
9
9
  from ._deps_tp import unwrap_tp
10
+ from .deps import _named_param
10
11
  from .signature import Signature
11
12
  from .types import AsyncFunc, DepOf, Func
12
13
 
@@ -41,7 +42,12 @@ def _dep_annotation(dep: DepOf[Any] | Callable[..., Any], /) -> Any:
41
42
  if isinstance(dep, Depends):
42
43
  return annotated(Any, dep)
43
44
 
44
- if _is_annotation(dep) or not callable(dep):
45
+ if _is_annotation(dep):
46
+ # bound, a marker is read under the made-up `__dep_arg_N` name, so it must name its own
47
+ _named_param(unwrap_tp(dep))
48
+ return dep
49
+
50
+ if not callable(dep):
45
51
  return dep
46
52
 
47
53
  return annotated(Any, Depends(dep))
@@ -0,0 +1,90 @@
1
+ import email.message
2
+ import json
3
+ from typing import Any
4
+
5
+ from fastapi import Request, params
6
+ from fastapi._compat import Undefined
7
+ from fastapi.dependencies.models import Dependant
8
+ from fastapi.dependencies.utils import _get_flat_body_params, _should_embed_body_fields
9
+ from fastapi.routing import APIRoute
10
+
11
+ from .types import BoundConnection
12
+
13
+ type RequestBody = tuple[Any, bool]
14
+
15
+ BODY_CACHE_KEY = "fastapi_injected_body"
16
+
17
+
18
+ class InvalidBodyError(ValueError):
19
+ def __init__(self, errors: list[Any], /) -> None:
20
+ super().__init__(errors)
21
+ self.errors = errors
22
+
23
+
24
+ def _is_json_content_type(content_type: str, /) -> bool:
25
+ message = email.message.Message()
26
+ message["content-type"] = content_type
27
+ subtype = message.get_content_subtype()
28
+
29
+ return message.get_content_maintype() == "application" and (subtype == "json" or subtype.endswith("+json"))
30
+
31
+
32
+ async def _read_body(request: Request, *, is_form: bool) -> Any:
33
+ if is_form:
34
+ form = await request.form()
35
+ # closing a form twice is harmless
36
+ request.scope["fastapi_middleware_astack"].push_async_callback(form.close)
37
+
38
+ return form
39
+
40
+ if not (body := await request.body()):
41
+ return Undefined
42
+
43
+ if not _is_json_content_type(request.headers.get("content-type", "")):
44
+ return body
45
+
46
+ try:
47
+ return await request.json()
48
+ except json.JSONDecodeError as exc:
49
+ raise InvalidBodyError(
50
+ [
51
+ {
52
+ "type": "json_invalid",
53
+ "loc": ("body", exc.pos),
54
+ "msg": "JSON decode error",
55
+ "input": {},
56
+ "ctx": {"error": exc.msg},
57
+ },
58
+ ],
59
+ ) from exc
60
+
61
+
62
+ def _route_embeds(request: Request, /) -> bool:
63
+ match request.scope.get("route"):
64
+ case APIRoute(_embed_body_fields=embed):
65
+ return embed
66
+
67
+ return False
68
+
69
+
70
+ async def request_body(request: BoundConnection, dependant: Dependant, /) -> RequestBody:
71
+ if not isinstance(request, Request) or not (fields := _get_flat_body_params(dependant)):
72
+ return Undefined, False
73
+
74
+ is_form = any(isinstance(field.field_info, params.Form) for field in fields)
75
+
76
+ # parsed once per request
77
+ cache: dict[bool, Any] = request.scope[BODY_CACHE_KEY]
78
+
79
+ if is_form not in cache:
80
+ cache[is_form] = await _read_body(request, is_form=is_form)
81
+
82
+ # read the body the way the route does
83
+ return cache[is_form], _route_embeds(request) or _should_embed_body_fields(fields)
84
+
85
+
86
+ __all__ = [
87
+ "BODY_CACHE_KEY",
88
+ "InvalidBodyError",
89
+ "request_body",
90
+ ]
@@ -37,7 +37,7 @@ def _cache_key(key: DependencyCacheKey, /) -> DependencyCacheKey:
37
37
  # done, the entry has to stay reachable for the rest of the context
38
38
  call, *rest = key
39
39
 
40
- return (unwrap_proxy(call), *rest) # type: ignore[ty:invalid-return-type]
40
+ return (unwrap_proxy(call), *rest) # type: ignore[ty:invalid-explicit-return]
41
41
 
42
42
 
43
43
  class ContextCache(MakeDataclass, MutableMapping[DependencyCacheKey, Any]):
@@ -14,7 +14,7 @@ from ._deps_tp import unwrap_tp
14
14
  def annotated(tp: Any, /, *metadata: Any) -> Any:
15
15
  # `Annotated[...]` goes through typing's own cache, which holds on to the last
16
16
  # aliases it built - and with them whatever value a runtime marker carries
17
- return typing._AnnotatedAlias(tp, metadata) # type: ignore[ty:unresolved-attribute] # noqa: SLF001
17
+ return typing._AnnotatedAlias(tp, metadata) # type: ignore[ty:missing-attribute] # noqa: SLF001
18
18
 
19
19
 
20
20
  def is_static_call(call: Any, /) -> bool:
@@ -1,3 +1,4 @@
1
+ import sys
1
2
  import types
2
3
  import typing
3
4
  from collections.abc import Callable
@@ -10,10 +11,23 @@ from typing_inspection.typing_objects import is_typealiastype
10
11
  from .types import ArgMarker, HasDependsHook
11
12
 
12
13
 
14
+ def _alias_value(alias: Any, /) -> Any:
15
+ try:
16
+ return alias.__value__
17
+ except NameError:
18
+ # a `TYPE_CHECKING`-only name: leave it a forward reference
19
+ if sys.version_info < (3, 14):
20
+ raise
21
+
22
+ from annotationlib import Format, call_evaluate_function # noqa: PLC0415
23
+
24
+ return call_evaluate_function(alias.evaluate_value, Format.FORWARDREF)
25
+
26
+
13
27
  def unwrap_tp(tp: Any) -> Any:
14
28
  # PEP 695 aliases can be nested, e.g. `type A = B` where `type B = Annotated[...]`
15
29
  while is_typealiastype(tp):
16
- tp = tp.__value__
30
+ tp = _alias_value(tp)
17
31
 
18
32
  return tp
19
33
 
@@ -0,0 +1,63 @@
1
+ import inspect
2
+ from collections.abc import Callable
3
+ from functools import cache
4
+ from typing import TYPE_CHECKING, Annotated, Any
5
+
6
+ from fastapi import Depends, HTTPException, status
7
+
8
+ from ._bind import _dep_annotation
9
+ from ._calls import is_static_annotation
10
+ from ._deps_tp import unwrap_tp
11
+
12
+
13
+ def not_found() -> Exception:
14
+ return HTTPException(status.HTTP_404_NOT_FOUND, "Not found")
15
+
16
+
17
+ def _build(annotation: Any, error: Callable[[], BaseException], /) -> Callable[..., Any]:
18
+ async def require(value: Any) -> Any:
19
+ if value is None:
20
+ raise error()
21
+
22
+ return value
23
+
24
+ require.__signature__ = inspect.Signature( # type: ignore[ty:missing-attribute]
25
+ [inspect.Parameter("value", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=annotation)],
26
+ )
27
+
28
+ return require
29
+
30
+
31
+ # one callable per source dependency, so FastAPI shares its result within a request
32
+ _build_static = cache(_build)
33
+
34
+
35
+ def not_none(tp: Any, dep: Any, error: Callable[[], BaseException] = not_found, /) -> Any:
36
+ annotation = unwrap_tp(_dep_annotation(dep))
37
+ build = _build_static if is_static_annotation(annotation) else _build
38
+
39
+ return Annotated[tp, Depends(build(annotation, error))]
40
+
41
+
42
+ if TYPE_CHECKING:
43
+ from typing import Annotated as NotNone
44
+ else:
45
+
46
+ class NotNone:
47
+ """`NotNone[T, dep]`: what `dep` resolves to, or `error()` raised when it is `None` (404 by default)."""
48
+
49
+ def __class_getitem__(cls, item: Any) -> Any:
50
+ match item:
51
+ case (tp, dep):
52
+ return not_none(tp, dep)
53
+ case (tp, dep, error):
54
+ return not_none(tp, dep, error)
55
+ case _:
56
+ raise TypeError(f"NotNone[...] takes a type, a dependency and optionally an error, got {item!r}")
57
+
58
+
59
+ __all__ = [
60
+ "NotNone",
61
+ "not_found",
62
+ "not_none",
63
+ ]