fastapi-injected 0.4.3__tar.gz → 0.5.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.4.3 → fastapi_injected-0.5.1}/PKG-INFO +67 -9
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/README.md +66 -8
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/__init__.py +11 -1
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_bind.py +17 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/ctx.py +36 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/ext.py +18 -2
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/fastapi.py +74 -13
- fastapi_injected-0.5.1/fastapi_injected/openapi.py +130 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/overrides.py +1 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/reflect/_routes.py +24 -11
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/signature.py +41 -4
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/pyproject.toml +1 -1
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_bind.py +26 -1
- fastapi_injected-0.5.1/tests/test_context_value.py +85 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_fastapi.py +122 -4
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_injected.py +11 -1
- fastapi_injected-0.5.1/tests/test_openapi.py +149 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_reflect.py +63 -2
- fastapi_injected-0.5.1/tests/test_signature.py +107 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/uv.lock +1 -1
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.github/dependabot.yml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.github/workflows/automerge.yml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.github/workflows/lint.yml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.github/workflows/publish.yml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.github/workflows/test.yml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.gitignore +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/.pre-commit-config.yaml +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/LICENSE +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_body.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_cache.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_calls.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_dataclass.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_deps_tp.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_given.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_injected.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_not_none.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_overrides.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/_rlock.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/deps.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/inject.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/reflect/__init__.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/reflect/_dependant.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/reflect/_openapi.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/resolve.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/fastapi_injected/types.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/__init__.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/__init__.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/annotations.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/arg.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/bind.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/ctx.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/dataclass.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/deps.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/errors.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/given.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/inject.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/injected.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/integration.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/markers.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/overrides.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/_typing/resolve.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/conftest.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/deps.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/ext/__init__.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/ext/test_pydantic_ai.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_body.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_body_reads.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_cache.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_calls.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_concurrency.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_ctx.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_dataclass.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_default_app.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_dependant_cache.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_errors.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_given.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_inject.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_not_none.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_overrides.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_request_params.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_resolve.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_rlock.py +0 -0
- {fastapi_injected-0.4.3 → fastapi_injected-0.5.1}/tests/test_type_checking_aliases.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: fastapi-injected
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.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>
|
|
@@ -185,6 +185,27 @@ async with injection_ctx(request=request):
|
|
|
185
185
|
|
|
186
186
|
Analysing a dependency is the expensive part of resolving one, so the result is cached — keyed by the dependency itself, not by whatever object carried it, so nothing that only passed through is kept alive. Only dependencies written in source code are cached this way: functions and classes, and annotations built from them. One made at runtime — `Given(...)`, a `MakeInjected` or `bind_deps` result, an object that brings its own `Depends` — is analysed again on every resolve, and FastAPI never gets to keep it: what it carries is released with the resolve instead of living as long as the process. `clear_dependant_cache()` drops the cache, for long-lived processes and test suites that want the memory back.
|
|
187
187
|
|
|
188
|
+
### Values scoped to a context
|
|
189
|
+
|
|
190
|
+
`ContextValue` is a `ContextVar` that lives as long as an injection context - inside a route, as long as the request. `set` writes to the current context, `get` reads the nearest one that has it: a nested context sees the value, but what it sets stays in it.
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from fastapi_injected import ContextValue
|
|
194
|
+
|
|
195
|
+
tenant = ContextValue[str]("tenant", default="public")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def set_tenant(x_tenant: Annotated[str, Header()]) -> None:
|
|
199
|
+
tenant.set(x_tenant)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.get("/", dependencies=[Depends(set_tenant)])
|
|
203
|
+
async def route() -> str:
|
|
204
|
+
return tenant.get() # this request's tenant
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Without a default, `get` raises `LookupError` when nothing set it; `set` outside a context raises `NoInjectionContextError`.
|
|
208
|
+
|
|
188
209
|
### Overriding dependencies
|
|
189
210
|
|
|
190
211
|
`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:
|
|
@@ -386,8 +407,25 @@ class IsOwner(MakeInjected):
|
|
|
386
407
|
await resolve(IsOwner(doc=Given(doc), role=RoleDep))
|
|
387
408
|
```
|
|
388
409
|
|
|
410
|
+
The call has to be an `async def`; a sync one raises `NotAsyncError`, as it does for `bind_deps` and `remap_dep_args`.
|
|
411
|
+
|
|
389
412
|
It is a `MakeDataclass`, so instances built from equal markers are equal — and therefore one dependency, resolved once per context and overridable as a whole. For callables that are not dataclasses, the two halves of the binding are available on their own: `signature_with_deps(func, deps)` builds the signature, and `remap_dep_args` turns the arguments it names back into positional ones.
|
|
390
413
|
|
|
414
|
+
### Objects that bring their own `Depends`
|
|
415
|
+
|
|
416
|
+
An object with a `__get_depends__()` method is resolved through the `Depends` it returns instead of its own call - by `resolve`, `as_depends`, `add_route_dependency` and `reflect`. The protocol is `fastapi_injected.types.HasDependsHook`:
|
|
417
|
+
|
|
418
|
+
```python
|
|
419
|
+
class Guarded:
|
|
420
|
+
def __call__(self) -> None: ...
|
|
421
|
+
|
|
422
|
+
def __get_depends__(self) -> params.Depends:
|
|
423
|
+
return Depends(require_admin, use_cache=False)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
await resolve(Guarded()) # resolves `require_admin`
|
|
427
|
+
```
|
|
428
|
+
|
|
391
429
|
### Inspecting annotations
|
|
392
430
|
|
|
393
431
|
`fastapi_injected.ext` holds a few helpers for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
|
|
@@ -395,6 +433,10 @@ It is a `MakeDataclass`, so instances built from equal markers are equal — and
|
|
|
395
433
|
- `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
|
|
396
434
|
- `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
|
|
397
435
|
- `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
|
|
436
|
+
- `is_request_param(tp)` — whether `tp` carries `Header()`, `Query()`, `Path()`, `Cookie()` or a body marker.
|
|
437
|
+
- `unwrap_tp(tp)` — the value of a PEP 695 `type` alias, through nested aliases.
|
|
438
|
+
- `annotated(tp, *metadata)` — `Annotated[tp, *metadata]` without typing's cache, which would keep runtime markers alive.
|
|
439
|
+
- `as_depends(dep)` — the `Depends` for a marker, a `__get_depends__` object or a callable (`DependsSource`).
|
|
398
440
|
|
|
399
441
|
### Reflecting on apps and dependency trees
|
|
400
442
|
|
|
@@ -425,21 +467,34 @@ assert list(iter_security(route.dependant)) == [(bearer, ["items:write"])]
|
|
|
425
467
|
- `match_route(app, request_or_scope)` — `(path_template, route)` for the route that would handle a request, through mounts, hosts and included routers; `None` when nothing matches. Useful in middleware, where `request.scope["route"]` is not set yet.
|
|
426
468
|
- `iter_params(root)` — `(dependant, kind, field)` for every path, query, header, cookie and body parameter in the tree.
|
|
427
469
|
- `response_type(route, *, strip=True)` — the route's response type, falling back to the endpoint's return annotation, with `Annotated` and `| None` stripped unless `strip=False`.
|
|
428
|
-
- `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function.
|
|
470
|
+
- `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function. `globalns=`/`localns=` add names its annotations need beyond the module of `func`, and `include_return=True` keeps the return annotation.
|
|
429
471
|
- `.add(*parameters)` — extra keyword-only parameters before `**kwargs`; names already present are kept as they are.
|
|
430
472
|
- `.drop(*names)` and `.update(name, **changes)` — drop parameters a wrapper consumes itself, or change one parameter's annotation, default or kind.
|
|
431
473
|
- `.add_dep(name, dep, *, annotation=Any)` — a parameter FastAPI resolves with a `Depends`/`Security` marker or a callable.
|
|
432
474
|
- `.prepend(*parameters)`, `.rename(old, new)` and `.returns(annotation)` — positional parameters at the front, a renamed parameter, a new return annotation.
|
|
433
475
|
- `Signature.role(parameter)` — which `ParamRole` a parameter plays: `dep` for `Dep[...]` or a `Depends` default, `request` for `Header()`/`Query()`/..., `arg` for `Arg[...]`, `plain` otherwise. `.select(*roles)` yields the parameters with those roles; `.annotations` and `.defaults` are name-to-value mappings of what is declared.
|
|
434
476
|
- `.wrap(func)` — a forwarder to `func`, async when `func` is, carrying this signature; `.apply(func)` sets the signature on `func` itself.
|
|
435
|
-
- `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
|
|
477
|
+
- `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` or `APIWebSocketRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
|
|
436
478
|
- `add_lifespan(app_or_router, lifespan)` — run a lifespan inside the one already set, merging the state both yield, for libraries that need a startup step on an app they did not create.
|
|
437
479
|
|
|
438
480
|
`root` for the dependency helpers is a `Dependant`, a `Depends(...)` marker or a plain callable; `as_dependant` is the conversion they share. A plain callable is read the way FastAPI would, with `Injected` defaults treated as dependencies.
|
|
439
481
|
|
|
482
|
+
### Adding to the OpenAPI schema
|
|
483
|
+
|
|
484
|
+
`fastapi_injected.openapi` gives libraries one shared `app.openapi` to add to, instead of each replacing it. The schema is cached in `app.openapi_schema` and built again when routes change, or after `invalidate_openapi(app)`.
|
|
485
|
+
|
|
486
|
+
- `add_openapi_hook(app, hook)` — `hook(app, schema)` post-processes the schema, in the order hooks were added; it changes `schema` in place or returns a new one.
|
|
487
|
+
- `__doc_depends__(methods)` — dependencies a call resolves itself, documented for every route that has it anywhere in its dependency tree (`HasDocDepends`, `iter_doc_depends(route)`). `add_openapi(app)` enables it without a hook.
|
|
488
|
+
|
|
489
|
+
A custom `app.openapi` is kept, and hooks run on its result.
|
|
490
|
+
|
|
491
|
+
```python
|
|
492
|
+
add_openapi_hook(app, lambda app, schema: {**schema, "x-version": "1"})
|
|
493
|
+
```
|
|
494
|
+
|
|
440
495
|
### FastAPI request integration
|
|
441
496
|
|
|
442
|
-
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. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request
|
|
497
|
+
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. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request and binds it to the route's connection once the route is found - before or after routers are included. FastAPI is patched by `add_injection` or `InjectionMiddleware`, not on import. Add it after your other middleware, so the context is open for them too:
|
|
443
498
|
|
|
444
499
|
```python
|
|
445
500
|
from fastapi import FastAPI
|
|
@@ -466,6 +521,8 @@ with set_default_app(test_app): # only inside the block
|
|
|
466
521
|
await job()
|
|
467
522
|
```
|
|
468
523
|
|
|
524
|
+
A `resolve()` failing inside a route answers with a 422, or closes a websocket: `add_injection` registers `dependency_resolution_handler` unless a handler for `DependencyResolutionError` exists or `handle_resolution_errors=False` is passed.
|
|
525
|
+
|
|
469
526
|
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
527
|
|
|
471
528
|
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).
|
|
@@ -526,19 +583,20 @@ The root package is what you need to use the library, and the surface a release
|
|
|
526
583
|
| --- | --- |
|
|
527
584
|
| Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
|
|
528
585
|
| Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
|
|
529
|
-
| Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
|
|
586
|
+
| Contexts and overrides | `InjectionContext`, `injection_ctx`, `ContextValue`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
|
|
530
587
|
| FastAPI integration | `add_injection` |
|
|
531
|
-
| Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
|
|
588
|
+
| Errors | `DependencyResolutionError`, `NoInjectionContextError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
|
|
532
589
|
|
|
533
590
|
Code that builds on the library imports from the submodule that owns the piece. These are public too:
|
|
534
591
|
|
|
535
592
|
| Module | Names |
|
|
536
593
|
| --- | --- |
|
|
537
|
-
| `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `strip_annotation`, `as_depends`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `UnboundDepArgsError` |
|
|
594
|
+
| `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `is_request_param`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `unwrap_tp`, `strip_annotation`, `annotated`, `as_depends`, `DependsSource`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `NotAsyncError`, `UnboundDepArgsError` |
|
|
538
595
|
| `fastapi_injected.types` | `DepOf`, `ArgMarker`, `HasDependsHook`, and the typing vocabulary the signatures are written in — `DepReturn`, `DepShape`, `DepDecl`, `AsyncFunc`, `Coro`, `BoundConnection`, `DependencyCache` and friends |
|
|
539
|
-
| `fastapi_injected.overrides` | `Overrides`, `OverridesProvider` |
|
|
596
|
+
| `fastapi_injected.overrides` | `Overrides`, `OverridesProvider`, `OverrideBlock` |
|
|
540
597
|
| `fastapi_injected.signature` | `Signature`, `ParamRole` |
|
|
541
|
-
| `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `MissingDependencyCacheError` |
|
|
598
|
+
| `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `dependency_resolution_handler`, `install_dependency_cache`, `MissingDependencyCacheError` |
|
|
599
|
+
| `fastapi_injected.openapi` | `add_openapi_hook`, `add_openapi`, `invalidate_openapi`, `HasDocDepends`, `iter_doc_depends`, `OpenAPIHook` |
|
|
542
600
|
| `fastapi_injected.reflect` | `iter_dependant`, `iter_calls`, `iter_security`, `iter_params`, `find_dependant`, `iter_overridden`, `iter_routes`, `iter_api_routes`, `iter_routes_where`, `find_route`, `match_route`, `iter_routers`, `response_type`, `add_route_dependency`, `add_lifespan`, `iter_operations`, `operation_for`, `as_dependant` |
|
|
543
601
|
|
|
544
602
|
Anything else, including every module whose name starts with an underscore, is machinery that can change in a patch release.
|
|
@@ -163,6 +163,27 @@ async with injection_ctx(request=request):
|
|
|
163
163
|
|
|
164
164
|
Analysing a dependency is the expensive part of resolving one, so the result is cached — keyed by the dependency itself, not by whatever object carried it, so nothing that only passed through is kept alive. Only dependencies written in source code are cached this way: functions and classes, and annotations built from them. One made at runtime — `Given(...)`, a `MakeInjected` or `bind_deps` result, an object that brings its own `Depends` — is analysed again on every resolve, and FastAPI never gets to keep it: what it carries is released with the resolve instead of living as long as the process. `clear_dependant_cache()` drops the cache, for long-lived processes and test suites that want the memory back.
|
|
165
165
|
|
|
166
|
+
### Values scoped to a context
|
|
167
|
+
|
|
168
|
+
`ContextValue` is a `ContextVar` that lives as long as an injection context - inside a route, as long as the request. `set` writes to the current context, `get` reads the nearest one that has it: a nested context sees the value, but what it sets stays in it.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
from fastapi_injected import ContextValue
|
|
172
|
+
|
|
173
|
+
tenant = ContextValue[str]("tenant", default="public")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def set_tenant(x_tenant: Annotated[str, Header()]) -> None:
|
|
177
|
+
tenant.set(x_tenant)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@app.get("/", dependencies=[Depends(set_tenant)])
|
|
181
|
+
async def route() -> str:
|
|
182
|
+
return tenant.get() # this request's tenant
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Without a default, `get` raises `LookupError` when nothing set it; `set` outside a context raises `NoInjectionContextError`.
|
|
186
|
+
|
|
166
187
|
### Overriding dependencies
|
|
167
188
|
|
|
168
189
|
`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:
|
|
@@ -364,8 +385,25 @@ class IsOwner(MakeInjected):
|
|
|
364
385
|
await resolve(IsOwner(doc=Given(doc), role=RoleDep))
|
|
365
386
|
```
|
|
366
387
|
|
|
388
|
+
The call has to be an `async def`; a sync one raises `NotAsyncError`, as it does for `bind_deps` and `remap_dep_args`.
|
|
389
|
+
|
|
367
390
|
It is a `MakeDataclass`, so instances built from equal markers are equal — and therefore one dependency, resolved once per context and overridable as a whole. For callables that are not dataclasses, the two halves of the binding are available on their own: `signature_with_deps(func, deps)` builds the signature, and `remap_dep_args` turns the arguments it names back into positional ones.
|
|
368
391
|
|
|
392
|
+
### Objects that bring their own `Depends`
|
|
393
|
+
|
|
394
|
+
An object with a `__get_depends__()` method is resolved through the `Depends` it returns instead of its own call - by `resolve`, `as_depends`, `add_route_dependency` and `reflect`. The protocol is `fastapi_injected.types.HasDependsHook`:
|
|
395
|
+
|
|
396
|
+
```python
|
|
397
|
+
class Guarded:
|
|
398
|
+
def __call__(self) -> None: ...
|
|
399
|
+
|
|
400
|
+
def __get_depends__(self) -> params.Depends:
|
|
401
|
+
return Depends(require_admin, use_cache=False)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
await resolve(Guarded()) # resolves `require_admin`
|
|
405
|
+
```
|
|
406
|
+
|
|
369
407
|
### Inspecting annotations
|
|
370
408
|
|
|
371
409
|
`fastapi_injected.ext` holds a few helpers for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
|
|
@@ -373,6 +411,10 @@ It is a `MakeDataclass`, so instances built from equal markers are equal — and
|
|
|
373
411
|
- `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
|
|
374
412
|
- `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
|
|
375
413
|
- `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
|
|
414
|
+
- `is_request_param(tp)` — whether `tp` carries `Header()`, `Query()`, `Path()`, `Cookie()` or a body marker.
|
|
415
|
+
- `unwrap_tp(tp)` — the value of a PEP 695 `type` alias, through nested aliases.
|
|
416
|
+
- `annotated(tp, *metadata)` — `Annotated[tp, *metadata]` without typing's cache, which would keep runtime markers alive.
|
|
417
|
+
- `as_depends(dep)` — the `Depends` for a marker, a `__get_depends__` object or a callable (`DependsSource`).
|
|
376
418
|
|
|
377
419
|
### Reflecting on apps and dependency trees
|
|
378
420
|
|
|
@@ -403,21 +445,34 @@ assert list(iter_security(route.dependant)) == [(bearer, ["items:write"])]
|
|
|
403
445
|
- `match_route(app, request_or_scope)` — `(path_template, route)` for the route that would handle a request, through mounts, hosts and included routers; `None` when nothing matches. Useful in middleware, where `request.scope["route"]` is not set yet.
|
|
404
446
|
- `iter_params(root)` — `(dependant, kind, field)` for every path, query, header, cookie and body parameter in the tree.
|
|
405
447
|
- `response_type(route, *, strip=True)` — the route's response type, falling back to the endpoint's return annotation, with `Annotated` and `| None` stripped unless `strip=False`.
|
|
406
|
-
- `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function.
|
|
448
|
+
- `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function. `globalns=`/`localns=` add names its annotations need beyond the module of `func`, and `include_return=True` keeps the return annotation.
|
|
407
449
|
- `.add(*parameters)` — extra keyword-only parameters before `**kwargs`; names already present are kept as they are.
|
|
408
450
|
- `.drop(*names)` and `.update(name, **changes)` — drop parameters a wrapper consumes itself, or change one parameter's annotation, default or kind.
|
|
409
451
|
- `.add_dep(name, dep, *, annotation=Any)` — a parameter FastAPI resolves with a `Depends`/`Security` marker or a callable.
|
|
410
452
|
- `.prepend(*parameters)`, `.rename(old, new)` and `.returns(annotation)` — positional parameters at the front, a renamed parameter, a new return annotation.
|
|
411
453
|
- `Signature.role(parameter)` — which `ParamRole` a parameter plays: `dep` for `Dep[...]` or a `Depends` default, `request` for `Header()`/`Query()`/..., `arg` for `Arg[...]`, `plain` otherwise. `.select(*roles)` yields the parameters with those roles; `.annotations` and `.defaults` are name-to-value mappings of what is declared.
|
|
412
454
|
- `.wrap(func)` — a forwarder to `func`, async when `func` is, carrying this signature; `.apply(func)` sets the signature on `func` itself.
|
|
413
|
-
- `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
|
|
455
|
+
- `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` or `APIWebSocketRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
|
|
414
456
|
- `add_lifespan(app_or_router, lifespan)` — run a lifespan inside the one already set, merging the state both yield, for libraries that need a startup step on an app they did not create.
|
|
415
457
|
|
|
416
458
|
`root` for the dependency helpers is a `Dependant`, a `Depends(...)` marker or a plain callable; `as_dependant` is the conversion they share. A plain callable is read the way FastAPI would, with `Injected` defaults treated as dependencies.
|
|
417
459
|
|
|
460
|
+
### Adding to the OpenAPI schema
|
|
461
|
+
|
|
462
|
+
`fastapi_injected.openapi` gives libraries one shared `app.openapi` to add to, instead of each replacing it. The schema is cached in `app.openapi_schema` and built again when routes change, or after `invalidate_openapi(app)`.
|
|
463
|
+
|
|
464
|
+
- `add_openapi_hook(app, hook)` — `hook(app, schema)` post-processes the schema, in the order hooks were added; it changes `schema` in place or returns a new one.
|
|
465
|
+
- `__doc_depends__(methods)` — dependencies a call resolves itself, documented for every route that has it anywhere in its dependency tree (`HasDocDepends`, `iter_doc_depends(route)`). `add_openapi(app)` enables it without a hook.
|
|
466
|
+
|
|
467
|
+
A custom `app.openapi` is kept, and hooks run on its result.
|
|
468
|
+
|
|
469
|
+
```python
|
|
470
|
+
add_openapi_hook(app, lambda app, schema: {**schema, "x-version": "1"})
|
|
471
|
+
```
|
|
472
|
+
|
|
418
473
|
### FastAPI request integration
|
|
419
474
|
|
|
420
|
-
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. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request
|
|
475
|
+
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. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request and binds it to the route's connection once the route is found - before or after routers are included. FastAPI is patched by `add_injection` or `InjectionMiddleware`, not on import. Add it after your other middleware, so the context is open for them too:
|
|
421
476
|
|
|
422
477
|
```python
|
|
423
478
|
from fastapi import FastAPI
|
|
@@ -444,6 +499,8 @@ with set_default_app(test_app): # only inside the block
|
|
|
444
499
|
await job()
|
|
445
500
|
```
|
|
446
501
|
|
|
502
|
+
A `resolve()` failing inside a route answers with a 422, or closes a websocket: `add_injection` registers `dependency_resolution_handler` unless a handler for `DependencyResolutionError` exists or `handle_resolution_errors=False` is passed.
|
|
503
|
+
|
|
447
504
|
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
505
|
|
|
449
506
|
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).
|
|
@@ -504,19 +561,20 @@ The root package is what you need to use the library, and the surface a release
|
|
|
504
561
|
| --- | --- |
|
|
505
562
|
| Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
|
|
506
563
|
| Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
|
|
507
|
-
| Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
|
|
564
|
+
| Contexts and overrides | `InjectionContext`, `injection_ctx`, `ContextValue`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
|
|
508
565
|
| FastAPI integration | `add_injection` |
|
|
509
|
-
| Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
|
|
566
|
+
| Errors | `DependencyResolutionError`, `NoInjectionContextError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
|
|
510
567
|
|
|
511
568
|
Code that builds on the library imports from the submodule that owns the piece. These are public too:
|
|
512
569
|
|
|
513
570
|
| Module | Names |
|
|
514
571
|
| --- | --- |
|
|
515
|
-
| `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `strip_annotation`, `as_depends`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `UnboundDepArgsError` |
|
|
572
|
+
| `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `is_request_param`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `unwrap_tp`, `strip_annotation`, `annotated`, `as_depends`, `DependsSource`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `NotAsyncError`, `UnboundDepArgsError` |
|
|
516
573
|
| `fastapi_injected.types` | `DepOf`, `ArgMarker`, `HasDependsHook`, and the typing vocabulary the signatures are written in — `DepReturn`, `DepShape`, `DepDecl`, `AsyncFunc`, `Coro`, `BoundConnection`, `DependencyCache` and friends |
|
|
517
|
-
| `fastapi_injected.overrides` | `Overrides`, `OverridesProvider` |
|
|
574
|
+
| `fastapi_injected.overrides` | `Overrides`, `OverridesProvider`, `OverrideBlock` |
|
|
518
575
|
| `fastapi_injected.signature` | `Signature`, `ParamRole` |
|
|
519
|
-
| `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `MissingDependencyCacheError` |
|
|
576
|
+
| `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `dependency_resolution_handler`, `install_dependency_cache`, `MissingDependencyCacheError` |
|
|
577
|
+
| `fastapi_injected.openapi` | `add_openapi_hook`, `add_openapi`, `invalidate_openapi`, `HasDocDepends`, `iter_doc_depends`, `OpenAPIHook` |
|
|
520
578
|
| `fastapi_injected.reflect` | `iter_dependant`, `iter_calls`, `iter_security`, `iter_params`, `find_dependant`, `iter_overridden`, `iter_routes`, `iter_api_routes`, `iter_routes_where`, `find_route`, `match_route`, `iter_routers`, `response_type`, `add_route_dependency`, `add_lifespan`, `iter_operations`, `operation_for`, `as_dependant` |
|
|
521
579
|
|
|
522
580
|
Anything else, including every module whose name starts with an underscore, is machinery that can change in a patch release.
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
from ._bind import bind_deps
|
|
2
2
|
from ._given import Given
|
|
3
3
|
from ._not_none import NotNone
|
|
4
|
-
from .ctx import
|
|
4
|
+
from .ctx import (
|
|
5
|
+
ContextValue,
|
|
6
|
+
InjectionContext,
|
|
7
|
+
NoInjectionContextError,
|
|
8
|
+
UnboundContextError,
|
|
9
|
+
injection_ctx,
|
|
10
|
+
set_default_app,
|
|
11
|
+
synthetic_request,
|
|
12
|
+
)
|
|
5
13
|
from .deps import DependencyResolutionError, UnnamedParamError
|
|
6
14
|
from .fastapi import add_injection
|
|
7
15
|
from .inject import inject
|
|
@@ -12,6 +20,7 @@ from .types import Arg, Dep, DepFactory, Injected
|
|
|
12
20
|
|
|
13
21
|
__all__ = [
|
|
14
22
|
"Arg",
|
|
23
|
+
"ContextValue",
|
|
15
24
|
"Dep",
|
|
16
25
|
"DepFactory",
|
|
17
26
|
"DependencyResolutionError",
|
|
@@ -19,6 +28,7 @@ __all__ = [
|
|
|
19
28
|
"Given",
|
|
20
29
|
"Injected",
|
|
21
30
|
"InjectionContext",
|
|
31
|
+
"NoInjectionContextError",
|
|
22
32
|
"NotADependencyError",
|
|
23
33
|
"NotNone",
|
|
24
34
|
"UnboundContextError",
|
|
@@ -88,7 +88,23 @@ def take_dep_args(kwargs: dict[str, Any], /) -> list[Any]:
|
|
|
88
88
|
return [kwargs.pop(dep_arg_name(index)) for index in indexes]
|
|
89
89
|
|
|
90
90
|
|
|
91
|
+
class NotAsyncError(TypeError):
|
|
92
|
+
def __init__(self, func: Callable[..., Any], /) -> None:
|
|
93
|
+
super().__init__(f"{func!r} must be an async function")
|
|
94
|
+
|
|
95
|
+
self.func = func
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _is_async_callable(func: Any, /) -> bool:
|
|
99
|
+
return inspect.iscoroutinefunction(inspect.unwrap(func)) or (
|
|
100
|
+
not inspect.isclass(func) and inspect.iscoroutinefunction(getattr(func, "__call__", None)) # noqa: B004
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
91
104
|
def remap_dep_args[**P, R](func: AsyncFunc[P, R], /) -> AsyncFunc[P, R]:
|
|
105
|
+
if not _is_async_callable(func):
|
|
106
|
+
raise NotAsyncError(func)
|
|
107
|
+
|
|
92
108
|
@wraps(func)
|
|
93
109
|
async def wrapper(*args: Any, **kwargs: Any) -> R:
|
|
94
110
|
return await func(*args, *take_dep_args(kwargs), **kwargs)
|
|
@@ -173,6 +189,7 @@ def bind_deps[**P, R](
|
|
|
173
189
|
|
|
174
190
|
|
|
175
191
|
__all__ = [
|
|
192
|
+
"NotAsyncError",
|
|
176
193
|
"UnboundDepArgsError",
|
|
177
194
|
"bind_deps",
|
|
178
195
|
"dep_arg_name",
|
|
@@ -24,6 +24,7 @@ from starlette.datastructures import FormData
|
|
|
24
24
|
from starlette.requests import HTTPConnection
|
|
25
25
|
from starlette.types import Message, Scope
|
|
26
26
|
from starlette.websockets import WebSocketState
|
|
27
|
+
from typing_extensions import sentinel
|
|
27
28
|
|
|
28
29
|
from ._body import BODY_CACHE_KEY
|
|
29
30
|
from ._cache import ContextCache, overridden_calls
|
|
@@ -225,6 +226,7 @@ class InjectionContext(MakeDataclass):
|
|
|
225
226
|
own_overrides: MutableMapping[Any, Any] = field(default_factory=dict, repr=False)
|
|
226
227
|
inherit_cache: bool = field(default=False, repr=False)
|
|
227
228
|
lock: RLock = field(default_factory=RLock, repr=False)
|
|
229
|
+
state: dict[ContextValue[Any], Any] = field(default_factory=dict, repr=False, compare=False)
|
|
228
230
|
|
|
229
231
|
@classmethod
|
|
230
232
|
def current(cls) -> Self | None:
|
|
@@ -301,12 +303,44 @@ class InjectionContext(MakeDataclass):
|
|
|
301
303
|
self,
|
|
302
304
|
parent=self,
|
|
303
305
|
dependency_cache={},
|
|
306
|
+
state={},
|
|
304
307
|
inherit_cache=True,
|
|
305
308
|
own_overrides=normalize_overrides(overrides, provider=provider),
|
|
306
309
|
),
|
|
307
310
|
)
|
|
308
311
|
|
|
309
312
|
|
|
313
|
+
class NoInjectionContextError(LookupError):
|
|
314
|
+
def __init__(self) -> None:
|
|
315
|
+
super().__init__("no injection context is open")
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
MISSING = sentinel("MISSING")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@dataclass(frozen=True, eq=False)
|
|
322
|
+
class ContextValue[T]:
|
|
323
|
+
name: str
|
|
324
|
+
default: T | MISSING = field(default=MISSING, kw_only=True)
|
|
325
|
+
|
|
326
|
+
def get(self) -> T:
|
|
327
|
+
if (ctx := InjectionContext.current()) is not None:
|
|
328
|
+
for owner in ctx.chain:
|
|
329
|
+
if self in owner.state:
|
|
330
|
+
return owner.state[self]
|
|
331
|
+
|
|
332
|
+
if self.default is MISSING:
|
|
333
|
+
raise LookupError(f"{self.name} is not set")
|
|
334
|
+
|
|
335
|
+
return self.default
|
|
336
|
+
|
|
337
|
+
def set(self, value: T, /) -> None:
|
|
338
|
+
if (ctx := InjectionContext.current()) is None:
|
|
339
|
+
raise NoInjectionContextError
|
|
340
|
+
|
|
341
|
+
ctx.state[self] = value
|
|
342
|
+
|
|
343
|
+
|
|
310
344
|
@contextmanager
|
|
311
345
|
def _reset_on_exit[T](var: ContextVar[T], token: Token[T], value: T, /) -> Generator[T]:
|
|
312
346
|
try:
|
|
@@ -483,7 +517,9 @@ async def ensure_injection_ctx(
|
|
|
483
517
|
|
|
484
518
|
|
|
485
519
|
__all__ = [
|
|
520
|
+
"ContextValue",
|
|
486
521
|
"InjectionContext",
|
|
522
|
+
"NoInjectionContextError",
|
|
487
523
|
"OverrideBlock",
|
|
488
524
|
"UnboundContextError",
|
|
489
525
|
"ensure_injection_ctx",
|
|
@@ -1,23 +1,39 @@
|
|
|
1
|
-
from ._bind import UnboundDepArgsError, remap_dep_args, signature_with_deps
|
|
1
|
+
from ._bind import NotAsyncError, UnboundDepArgsError, remap_dep_args, signature_with_deps
|
|
2
|
+
from ._calls import annotated
|
|
2
3
|
from ._dataclass import MakeDataclass
|
|
3
|
-
from ._deps_tp import
|
|
4
|
+
from ._deps_tp import (
|
|
5
|
+
DependsSource,
|
|
6
|
+
as_depends,
|
|
7
|
+
is_arg,
|
|
8
|
+
is_dep,
|
|
9
|
+
is_request_param,
|
|
10
|
+
strip_annotation,
|
|
11
|
+
unwrap_dep_dependency,
|
|
12
|
+
unwrap_dep_tp,
|
|
13
|
+
unwrap_tp,
|
|
14
|
+
)
|
|
4
15
|
from ._injected import MakeInjected
|
|
5
16
|
from .ctx import ensure_injection_ctx
|
|
6
17
|
from .deps import MissedDependencyError, clear_dependant_cache
|
|
7
18
|
|
|
8
19
|
__all__ = [
|
|
20
|
+
"DependsSource",
|
|
9
21
|
"MakeDataclass",
|
|
10
22
|
"MakeInjected",
|
|
11
23
|
"MissedDependencyError",
|
|
24
|
+
"NotAsyncError",
|
|
12
25
|
"UnboundDepArgsError",
|
|
26
|
+
"annotated",
|
|
13
27
|
"as_depends",
|
|
14
28
|
"clear_dependant_cache",
|
|
15
29
|
"ensure_injection_ctx",
|
|
16
30
|
"is_arg",
|
|
17
31
|
"is_dep",
|
|
32
|
+
"is_request_param",
|
|
18
33
|
"remap_dep_args",
|
|
19
34
|
"signature_with_deps",
|
|
20
35
|
"strip_annotation",
|
|
21
36
|
"unwrap_dep_dependency",
|
|
22
37
|
"unwrap_dep_tp",
|
|
38
|
+
"unwrap_tp",
|
|
23
39
|
]
|
|
@@ -1,18 +1,27 @@
|
|
|
1
|
-
from collections.abc import AsyncGenerator
|
|
1
|
+
from collections.abc import AsyncGenerator, Callable
|
|
2
2
|
from dataclasses import dataclass
|
|
3
|
-
from functools import wraps
|
|
4
|
-
from typing import
|
|
3
|
+
from functools import cache, wraps
|
|
4
|
+
from typing import Any, cast
|
|
5
5
|
|
|
6
|
-
from fastapi import
|
|
6
|
+
from fastapi import FastAPI, Request, Response, WebSocket, routing
|
|
7
7
|
from fastapi.dependencies import utils
|
|
8
|
+
from fastapi.dependencies.models import Dependant
|
|
9
|
+
from fastapi.dependencies.utils import _solve_generator, get_dependant
|
|
10
|
+
from fastapi.exception_handlers import (
|
|
11
|
+
request_validation_exception_handler,
|
|
12
|
+
websocket_request_validation_exception_handler,
|
|
13
|
+
)
|
|
14
|
+
from fastapi.exceptions import WebSocketRequestValidationError
|
|
8
15
|
from starlette.requests import HTTPConnection
|
|
9
|
-
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
16
|
+
from starlette.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
|
|
10
17
|
|
|
11
18
|
from ._cache import ContextCache
|
|
12
19
|
from .ctx import injection_ctx, set_default_app
|
|
20
|
+
from .deps import DependencyResolutionError
|
|
13
21
|
from .types import BoundConnection, DependencyCache, HasDependencyOverrides
|
|
14
22
|
|
|
15
23
|
_DEPENDENCY_CACHE_KEY = "__fastapi_injected_dependency_cache__"
|
|
24
|
+
_BOUND_KEY = "__fastapi_injected_bound__"
|
|
16
25
|
|
|
17
26
|
|
|
18
27
|
class MissingDependencyCacheError(Exception):
|
|
@@ -32,10 +41,11 @@ async def _unavailable_send(_: Message) -> None:
|
|
|
32
41
|
raise ConnectionNotAvailableError
|
|
33
42
|
|
|
34
43
|
|
|
35
|
-
|
|
36
|
-
_base_solve_dependencies = utils.solve_dependencies
|
|
44
|
+
_PATCHED_MARKER = "__fastapi_injected_patched__"
|
|
37
45
|
|
|
38
|
-
|
|
46
|
+
|
|
47
|
+
def _patched_solve_dependencies(base: Callable[..., Any], /) -> Callable[..., Any]:
|
|
48
|
+
@wraps(base)
|
|
39
49
|
async def _solve_dependencies(
|
|
40
50
|
*,
|
|
41
51
|
request: Request | WebSocket,
|
|
@@ -52,14 +62,29 @@ if not TYPE_CHECKING:
|
|
|
52
62
|
|
|
53
63
|
request.scope[_DEPENDENCY_CACHE_KEY] = dependency_cache
|
|
54
64
|
|
|
55
|
-
|
|
65
|
+
# the first solve of a request under `InjectionMiddleware` binds its context to the route's connection
|
|
66
|
+
if request.scope.get(_BOUND_KEY) is False:
|
|
67
|
+
await _solve_generator(
|
|
68
|
+
dependant=_bind_dependant(),
|
|
69
|
+
stack=request.scope["fastapi_inner_astack"],
|
|
70
|
+
sub_values={"connection": request},
|
|
71
|
+
request=request,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return await base(
|
|
56
75
|
request=request,
|
|
57
76
|
dependency_cache=dependency_cache,
|
|
58
77
|
**kwargs,
|
|
59
78
|
)
|
|
60
79
|
|
|
61
|
-
|
|
62
|
-
|
|
80
|
+
setattr(_solve_dependencies, _PATCHED_MARKER, True)
|
|
81
|
+
return _solve_dependencies
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def install_dependency_cache() -> None:
|
|
85
|
+
for module in (utils, routing):
|
|
86
|
+
if not getattr(module.solve_dependencies, _PATCHED_MARKER, False):
|
|
87
|
+
setattr(module, "solve_dependencies", _patched_solve_dependencies(module.solve_dependencies)) # noqa: B010
|
|
63
88
|
|
|
64
89
|
|
|
65
90
|
def _get_dependency_cache(connection: HTTPConnection) -> DependencyCache:
|
|
@@ -86,6 +111,12 @@ async def bind_injection_ctx(connection: HTTPConnection) -> AsyncGenerator[None]
|
|
|
86
111
|
if not isinstance(connection, Request | WebSocket): # pragma: no cover
|
|
87
112
|
raise TypeError(f"expected a Request or a WebSocket, got {type(connection).__name__}")
|
|
88
113
|
|
|
114
|
+
if connection.scope.get(_BOUND_KEY):
|
|
115
|
+
yield
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
connection.scope[_BOUND_KEY] = True
|
|
119
|
+
|
|
89
120
|
# the connection of the route: the middleware context, if any, was bound before routing
|
|
90
121
|
async with injection_ctx(
|
|
91
122
|
dependency_cache=_get_dependency_cache(connection),
|
|
@@ -95,10 +126,18 @@ async def bind_injection_ctx(connection: HTTPConnection) -> AsyncGenerator[None]
|
|
|
95
126
|
yield
|
|
96
127
|
|
|
97
128
|
|
|
129
|
+
@cache
|
|
130
|
+
def _bind_dependant() -> Dependant:
|
|
131
|
+
return get_dependant(path="", call=bind_injection_ctx)
|
|
132
|
+
|
|
133
|
+
|
|
98
134
|
@dataclass
|
|
99
135
|
class InjectionMiddleware:
|
|
100
136
|
app: ASGIApp
|
|
101
137
|
|
|
138
|
+
def __post_init__(self) -> None:
|
|
139
|
+
install_dependency_cache()
|
|
140
|
+
|
|
102
141
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
103
142
|
connection: BoundConnection
|
|
104
143
|
|
|
@@ -112,6 +151,7 @@ class InjectionMiddleware:
|
|
|
112
151
|
return
|
|
113
152
|
|
|
114
153
|
scope[_DEPENDENCY_CACHE_KEY] = cache = {}
|
|
154
|
+
scope[_BOUND_KEY] = False
|
|
115
155
|
|
|
116
156
|
async with injection_ctx(
|
|
117
157
|
dependency_cache=cache,
|
|
@@ -136,17 +176,36 @@ def _is_build_middleware_stack_patched(app: FastAPI) -> bool:
|
|
|
136
176
|
return getattr(app.build_middleware_stack, "__patched__", False)
|
|
137
177
|
|
|
138
178
|
|
|
179
|
+
async def dependency_resolution_handler(connection: HTTPConnection, exc: Exception) -> Response | None:
|
|
180
|
+
unresolved = cast("DependencyResolutionError", exc)
|
|
181
|
+
|
|
182
|
+
if isinstance(connection, WebSocket):
|
|
183
|
+
await websocket_request_validation_exception_handler(
|
|
184
|
+
connection,
|
|
185
|
+
WebSocketRequestValidationError(unresolved.errors),
|
|
186
|
+
)
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
return await request_validation_exception_handler(
|
|
190
|
+
cast("Request", connection),
|
|
191
|
+
unresolved.as_validation_error(),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
139
195
|
def add_injection(
|
|
140
196
|
app: FastAPI,
|
|
141
197
|
/,
|
|
198
|
+
*,
|
|
199
|
+
handle_resolution_errors: bool = True,
|
|
142
200
|
) -> None:
|
|
201
|
+
install_dependency_cache()
|
|
143
202
|
set_default_app(app)
|
|
144
203
|
|
|
145
204
|
if not _is_build_middleware_stack_patched(app):
|
|
146
205
|
_wrap_build_middleware_stack(app)
|
|
147
206
|
|
|
148
|
-
if
|
|
149
|
-
app.
|
|
207
|
+
if handle_resolution_errors and DependencyResolutionError not in app.exception_handlers:
|
|
208
|
+
app.add_exception_handler(DependencyResolutionError, cast("ExceptionHandler", dependency_resolution_handler))
|
|
150
209
|
|
|
151
210
|
|
|
152
211
|
__all__ = [
|
|
@@ -155,4 +214,6 @@ __all__ = [
|
|
|
155
214
|
"MissingDependencyCacheError",
|
|
156
215
|
"add_injection",
|
|
157
216
|
"bind_injection_ctx",
|
|
217
|
+
"dependency_resolution_handler",
|
|
218
|
+
"install_dependency_cache",
|
|
158
219
|
]
|