fastapi-cls-view 0.1.0__py3-none-any.whl

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 (32) hide show
  1. fastapi_cls_view/__init__.py +85 -0
  2. fastapi_cls_view/_internal/__init__.py +0 -0
  3. fastapi_cls_view/_internal/hooks/__init__.py +0 -0
  4. fastapi_cls_view/_internal/hooks/chain.py +102 -0
  5. fastapi_cls_view/_internal/hooks/collect.py +120 -0
  6. fastapi_cls_view/_internal/hooks/decorators.py +158 -0
  7. fastapi_cls_view/_internal/hooks/info.py +84 -0
  8. fastapi_cls_view/_internal/hooks/stream.py +139 -0
  9. fastapi_cls_view/_internal/inherit.py +62 -0
  10. fastapi_cls_view/_internal/member.py +85 -0
  11. fastapi_cls_view/_internal/routes/__init__.py +0 -0
  12. fastapi_cls_view/_internal/routes/binding.py +71 -0
  13. fastapi_cls_view/_internal/routes/context.py +56 -0
  14. fastapi_cls_view/_internal/routes/dependencies.py +71 -0
  15. fastapi_cls_view/_internal/routes/handled.py +27 -0
  16. fastapi_cls_view/_internal/routes/route.py +196 -0
  17. fastapi_cls_view/_internal/routes/route_class.py +67 -0
  18. fastapi_cls_view/_internal/view/__init__.py +0 -0
  19. fastapi_cls_view/_internal/view/config.py +45 -0
  20. fastapi_cls_view/_internal/view/fields.py +185 -0
  21. fastapi_cls_view/_internal/view/generics.py +82 -0
  22. fastapi_cls_view/_internal/view/markers.py +70 -0
  23. fastapi_cls_view/decorators.py +150 -0
  24. fastapi_cls_view/docs.py +150 -0
  25. fastapi_cls_view/errors.py +150 -0
  26. fastapi_cls_view/py.typed +0 -0
  27. fastapi_cls_view/types.py +154 -0
  28. fastapi_cls_view/views.py +293 -0
  29. fastapi_cls_view-0.1.0.dist-info/METADATA +197 -0
  30. fastapi_cls_view-0.1.0.dist-info/RECORD +32 -0
  31. fastapi_cls_view-0.1.0.dist-info/WHEEL +4 -0
  32. fastapi_cls_view-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,85 @@
1
+ from fastapi_cls_view._internal.hooks.decorators import error_hook, lifespan, request_hook
2
+ from fastapi_cls_view._internal.hooks.info import ViewHook
3
+ from fastapi_cls_view._internal.routes.context import CurrentRoute, RouteContext, current_route
4
+ from fastapi_cls_view._internal.routes.dependencies import ViewDependency, dependency
5
+ from fastapi_cls_view._internal.routes.route import ViewRoute
6
+ from fastapi_cls_view._internal.view.fields import ViewField
7
+
8
+ from .decorators import api_route, delete, get, head, options, patch, post, put, sse, trace, websocket
9
+ from .docs import Example, ResponseDoc, ResponseHeader, responds
10
+ from .errors import (
11
+ DecoratorUsageError,
12
+ MissingSelfError,
13
+ NotAViewRouteError,
14
+ OverrideError,
15
+ ReservedNameError,
16
+ StreamHookError,
17
+ UnboundRouteError,
18
+ UnknownClassKeywordsError,
19
+ UnknownDependencyError,
20
+ UnknownFieldError,
21
+ UnknownHookRouteError,
22
+ UnknownRouteError,
23
+ UnknownViewConfigError,
24
+ UnsupportedHookError,
25
+ UnsupportedViewOptionError,
26
+ ViewDependencyCycleError,
27
+ ViewError,
28
+ ViewNotReadyError,
29
+ )
30
+ from .types import APIRouteOptions, Handler, HookMode, RouteOptions, ViewConfig, WebSocketOptions
31
+ from .views import View
32
+
33
+ __all__ = [
34
+ "APIRouteOptions",
35
+ "CurrentRoute",
36
+ "DecoratorUsageError",
37
+ "Example",
38
+ "Handler",
39
+ "HookMode",
40
+ "MissingSelfError",
41
+ "NotAViewRouteError",
42
+ "OverrideError",
43
+ "ReservedNameError",
44
+ "ResponseDoc",
45
+ "ResponseHeader",
46
+ "RouteContext",
47
+ "RouteOptions",
48
+ "StreamHookError",
49
+ "UnboundRouteError",
50
+ "UnknownClassKeywordsError",
51
+ "UnknownDependencyError",
52
+ "UnknownFieldError",
53
+ "UnknownHookRouteError",
54
+ "UnknownRouteError",
55
+ "UnknownViewConfigError",
56
+ "UnsupportedHookError",
57
+ "UnsupportedViewOptionError",
58
+ "View",
59
+ "ViewConfig",
60
+ "ViewDependency",
61
+ "ViewDependencyCycleError",
62
+ "ViewError",
63
+ "ViewField",
64
+ "ViewHook",
65
+ "ViewNotReadyError",
66
+ "ViewRoute",
67
+ "WebSocketOptions",
68
+ "api_route",
69
+ "current_route",
70
+ "delete",
71
+ "dependency",
72
+ "error_hook",
73
+ "get",
74
+ "head",
75
+ "lifespan",
76
+ "options",
77
+ "patch",
78
+ "post",
79
+ "put",
80
+ "request_hook",
81
+ "responds",
82
+ "sse",
83
+ "trace",
84
+ "websocket",
85
+ ]
File without changes
File without changes
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from functools import partial, wraps
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from fastapi_injected.ext import NotAsyncError, is_async_callable
8
+
9
+ from fastapi_cls_view._internal.routes.binding import run, split_view
10
+ from fastapi_cls_view._internal.routes.handled import record_handled
11
+ from fastapi_cls_view.types import Handler
12
+
13
+ from .collect import closest_error_hook
14
+
15
+ if TYPE_CHECKING:
16
+ from fastapi_cls_view.types import ErrorHook, RequestHook
17
+
18
+
19
+ def _after(hook: Callable[..., Any], view: Any, handler: Handler[Any], /) -> Any:
20
+ return hook(view, handler())
21
+
22
+
23
+ async def _async_after(hook: Callable[..., Any], view: Any, handler: Handler[Any], /) -> Any:
24
+ return await run(hook, view, await handler())
25
+
26
+
27
+ type _After = Callable[[Callable[..., Any], Any, Handler[Any]], Any]
28
+
29
+
30
+ def _layer(hook: RequestHook, view: Any, handler: Handler[Any], after: _After, /) -> Handler[Any]:
31
+ match hook.info.mode:
32
+ case "wrap":
33
+ return partial(hook.func, view, handler)
34
+ case _:
35
+ return partial(after, hook.func, view, handler)
36
+
37
+
38
+ def _stack(hooks: list[RequestHook], view: Any, handler: Handler[Any], after: _After, /) -> Handler[Any]:
39
+ # as pydantic applies validators: each hook wraps the ones defined before it
40
+ for hook in hooks:
41
+ handler = _layer(hook, view, handler, after)
42
+
43
+ return handler
44
+
45
+
46
+ def _method_hook(errors: list[ErrorHook], view: Any, exc: Exception, /) -> ErrorHook | None:
47
+ # one hook wins over both kinds: a closer classmethod one answers in the route class
48
+ if (hook := closest_error_hook(errors, exc)) is None or hook.on_class:
49
+ return None
50
+
51
+ record_handled(view, exc)
52
+ return hook
53
+
54
+
55
+ def _handle(errors: list[ErrorHook], view: Any, exc: Exception, /) -> Any:
56
+ # `None`: no hook answered, the error goes on
57
+ return None if (hook := _method_hook(errors, view, exc)) is None else hook.func(view, exc)
58
+
59
+
60
+ async def _async_handle(errors: list[ErrorHook], view: Any, exc: Exception, /) -> Any:
61
+ return None if (hook := _method_hook(errors, view, exc)) is None else await run(hook.func, view, exc)
62
+
63
+
64
+ def hooked(func: Callable[..., Any], self_name: str, hooks: list[RequestHook], errors: list[ErrorHook], /) -> Any:
65
+ if not any(is_async_callable(f) for f in (func, *(hook.func for hook in (*hooks, *errors)))):
66
+
67
+ @wraps(func)
68
+ def call(*args: Any, **kwargs: Any) -> Any:
69
+ view, args = split_view(self_name, args, kwargs)
70
+
71
+ try:
72
+ return _stack(hooks, view, partial(func, view, *args, **kwargs), _after)()
73
+ except Exception as exc:
74
+ if (response := _handle(errors, view, exc)) is None:
75
+ raise
76
+
77
+ return response
78
+
79
+ return call
80
+
81
+ for hook in hooks:
82
+ if hook.info.mode == "wrap" and not is_async_callable(hook.func):
83
+ raise NotAsyncError(hook.func)
84
+
85
+ @wraps(func)
86
+ async def async_call(*args: Any, **kwargs: Any) -> Any:
87
+ view, args = split_view(self_name, args, kwargs)
88
+
89
+ try:
90
+ return await _stack(hooks, view, partial(run, func, view, *args, **kwargs), _async_after)()
91
+ except Exception as exc:
92
+ if (response := await _async_handle(errors, view, exc)) is None:
93
+ raise
94
+
95
+ return response
96
+
97
+ return async_call
98
+
99
+
100
+ __all__ = [
101
+ "hooked",
102
+ ]
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncGenerator, Callable
4
+ from contextlib import AsyncExitStack, asynccontextmanager
5
+ from types import FunctionType
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from typing_extensions import TypeIs
9
+
10
+ from fastapi_cls_view._internal.inherit import collect_inherited, overrider
11
+ from fastapi_cls_view.errors import UnknownHookRouteError, UnsupportedHookError
12
+ from fastapi_cls_view.types import (
13
+ AnyViewHook,
14
+ AnyViewRoute,
15
+ ErrorHook,
16
+ HookMode,
17
+ LifespanHook,
18
+ RequestHook,
19
+ ViewHooks,
20
+ )
21
+
22
+ from .info import ErrorHookInfo, HookInfo, LifespanHookInfo, RequestHookInfo, ViewHook
23
+ from .stream import is_stream
24
+
25
+ if TYPE_CHECKING:
26
+ from fastapi_cls_view.views import View
27
+
28
+
29
+ def view_lifespan(view: type[View], hooks: list[LifespanHook], /) -> Callable[[Any], Any]:
30
+ # each in order, the bases' first; shut down in reverse
31
+ @asynccontextmanager
32
+ async def view_lifespan(app: Any) -> AsyncGenerator[None]:
33
+ async with AsyncExitStack() as stack:
34
+ for hook in hooks:
35
+ await stack.enter_async_context(asynccontextmanager(hook.func)(view, app))
36
+
37
+ yield
38
+
39
+ return view_lifespan
40
+
41
+
42
+ def _is_hook[I: HookInfo](hook: AnyViewHook, kind: type[I], /) -> TypeIs[ViewHook[I]]:
43
+ return isinstance(hook.info, kind)
44
+
45
+
46
+ def lifespan_hooks(hooks: list[AnyViewHook], /) -> list[LifespanHook]:
47
+ return [hook for hook in hooks if _is_hook(hook, LifespanHookInfo)]
48
+
49
+
50
+ def request_hooks(hooks: list[AnyViewHook], /, *modes: HookMode) -> list[RequestHook]:
51
+ return [hook for hook in hooks if _is_hook(hook, RequestHookInfo) and hook.info.mode in modes]
52
+
53
+
54
+ def error_hooks(hooks: list[AnyViewHook], /, *, on_class: bool | None = None) -> list[ErrorHook]:
55
+ return [hook for hook in hooks if _is_hook(hook, ErrorHookInfo) and on_class in {None, hook.on_class}]
56
+
57
+
58
+ def closest_error_hook(hooks: list[ErrorHook], exc: Exception, /) -> ErrorHook | None:
59
+ # the closest exception type wins; on a tie, the one defined last - a subclass's
60
+ found: ErrorHook | None = None
61
+ closest: int | None = None
62
+
63
+ for hook in hooks:
64
+ distance = hook.info.distance(exc)
65
+
66
+ if distance is None:
67
+ continue
68
+
69
+ if closest is None or distance <= closest:
70
+ found, closest = hook, distance
71
+
72
+ return found
73
+
74
+
75
+ _override_hook = overrider("hook", "wrapped", (FunctionType, classmethod))
76
+
77
+
78
+ def collect_hooks(view: type[View], /) -> ViewHooks:
79
+ return collect_inherited(view, ViewHook, _override_hook)
80
+
81
+
82
+ def _unsupported(hook: AnyViewHook, route: AnyViewRoute, /) -> str | None:
83
+ match hook.info:
84
+ case RequestHookInfo(mode="before" | "wrap" | "teardown"):
85
+ return None
86
+ case _ if route.is_websocket:
87
+ return "a websocket route only runs `before`, `wrap` and `teardown` hooks"
88
+ case ErrorHookInfo() if not hook.on_class and is_stream(route.func):
89
+ return "a stream has started its response when it fails - use a `@classmethod` error hook"
90
+ case _:
91
+ return None
92
+
93
+
94
+ def check_hook_routes(view: type[View], /) -> None:
95
+ routes = view.__view_routes__
96
+ # a base's hook may name a route a subclass dropped, `users = None`
97
+ known = {name for base in view.__mro__ for name in base.__dict__.get("__view_routes__", {})}
98
+
99
+ for hook in view.__view_hooks__.values():
100
+ if isinstance(hook.info, LifespanHookInfo):
101
+ continue
102
+
103
+ if unknown := {*hook.info.routes} - known:
104
+ raise UnknownHookRouteError(hook.name, unknown)
105
+
106
+ # named explicitly: a `"*"` hook just skips the routes it can't run on
107
+ for name in {*hook.info.routes} & {*routes}:
108
+ if (reason := _unsupported(hook, routes[name])) is not None:
109
+ raise UnsupportedHookError(hook.name, name, reason)
110
+
111
+
112
+ __all__ = [
113
+ "check_hook_routes",
114
+ "closest_error_hook",
115
+ "collect_hooks",
116
+ "error_hooks",
117
+ "lifespan_hooks",
118
+ "request_hooks",
119
+ "view_lifespan",
120
+ ]
@@ -0,0 +1,158 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Callable, Sequence
5
+ from types import FunctionType
6
+ from typing import Any, Final, get_args, overload
7
+
8
+ from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
9
+ from starlette.exceptions import HTTPException
10
+ from typing_extensions import TypeIs
11
+
12
+ from fastapi_cls_view.errors import DecoratorUsageError
13
+ from fastapi_cls_view.types import (
14
+ ExceptionTypes,
15
+ Hookable,
16
+ HookMode,
17
+ )
18
+
19
+ from .info import ErrorHookInfo, HookInfo, LifespanHookInfo, RequestHookInfo, ViewHook
20
+
21
+ _MODES: Final = frozenset(get_args(HookMode.__value__))
22
+
23
+
24
+ def _method_kind(info: HookInfo, /) -> str:
25
+ match info:
26
+ # before the view is built, or without it
27
+ case RequestHookInfo(mode="request") | LifespanHookInfo():
28
+ return "class"
29
+ # a classmethod handles what building the view raises too, a method only the route's own errors
30
+ case ErrorHookInfo():
31
+ return "any"
32
+ case _:
33
+ return "instance"
34
+
35
+
36
+ def _hook[I: HookInfo](target: Any, info: I, /) -> ViewHook[I]:
37
+ match target:
38
+ case ViewHook():
39
+ raise DecoratorUsageError(f"{target.func!r} is already a hook - a method is one hook")
40
+ case FunctionType() if _method_kind(info) == "class":
41
+ raise DecoratorUsageError(f"{target!r} runs before the view is built: make it a `@classmethod`")
42
+ case classmethod(__func__=func) if _method_kind(info) == "instance":
43
+ raise DecoratorUsageError(f"{func!r} gets the view instance: make it a plain method")
44
+ case FunctionType(__name__=name) | classmethod(__func__=FunctionType(__name__=name)):
45
+ return ViewHook(name, target, info)
46
+ case _:
47
+ raise DecoratorUsageError(f"a hook decorates a method or classmethod of a view, got {target!r}")
48
+
49
+
50
+ def _is_exception_type(target: object, /) -> TypeIs[type[BaseException]]:
51
+ return isinstance(target, type) and issubclass(target, BaseException)
52
+
53
+
54
+ def _is_target(arg: object, /) -> bool:
55
+ return isinstance(arg, str) or _is_exception_type(arg)
56
+
57
+
58
+ def _routes(routes: Sequence[str], /) -> tuple[str, ...]:
59
+ if not all(isinstance(route, str) for route in routes):
60
+ raise DecoratorUsageError(f"a hook names its routes by their method names, got {routes!r}")
61
+
62
+ # `"*"` is every route, as in pydantic's `field_validator("*")`
63
+ if "*" in routes:
64
+ return ()
65
+
66
+ return tuple(routes)
67
+
68
+
69
+ def _decorator[I: HookInfo](info: I, /) -> Callable[[Any], ViewHook[I]]:
70
+ def decorator(target: Any, /) -> ViewHook[I]:
71
+ return _hook(target, info)
72
+
73
+ return decorator
74
+
75
+
76
+ @overload
77
+ def request_hook[F: Hookable](func: F, /) -> F: ...
78
+
79
+
80
+ @overload
81
+ def request_hook[F: Hookable](*routes: str, mode: HookMode = "after") -> Callable[[F], F]: ...
82
+
83
+
84
+ def request_hook(*args: Any, mode: HookMode = "after") -> Any:
85
+ if mode not in _MODES:
86
+ raise DecoratorUsageError(f"unknown hook mode {mode!r}, expected one of {sorted(_MODES)}")
87
+
88
+ match args:
89
+ case (target,) if not _is_target(target):
90
+ return _hook(target, RequestHookInfo(mode, ()))
91
+ case _ if any(_is_exception_type(arg) for arg in args):
92
+ raise DecoratorUsageError("exceptions are handled by `@error_hook(...)`, not `request_hook()`")
93
+ case _:
94
+ return _decorator(RequestHookInfo(mode, _routes(args)))
95
+
96
+
97
+ def _is_exceptions(target: object, /) -> TypeIs[ExceptionTypes]:
98
+ # as an `except` clause takes them: one type or a non-empty tuple
99
+ match target:
100
+ case tuple():
101
+ return bool(target) and all(_is_exception_type(tp) for tp in target)
102
+ case _:
103
+ return _is_exception_type(target)
104
+
105
+
106
+ # what a hook catches unless it names its exceptions: FastAPI's own errors already answer as they should
107
+ _NOT_BY_DEFAULT: Final = (HTTPException, RequestValidationError, WebSocketRequestValidationError)
108
+
109
+
110
+ def _error_info(exc: object, routes: tuple[Any, ...], /) -> ErrorHookInfo:
111
+ if exc is None:
112
+ return ErrorHookInfo(_routes(routes), (Exception,), _NOT_BY_DEFAULT)
113
+
114
+ if not _is_exceptions(exc):
115
+ raise DecoratorUsageError(f"an error hook handles an exception type or a tuple of them, got {exc!r}")
116
+
117
+ return ErrorHookInfo(_routes(routes), exc if isinstance(exc, tuple) else (exc,))
118
+
119
+
120
+ @overload
121
+ def error_hook[F: Hookable](func: F, /) -> F: ...
122
+
123
+
124
+ @overload
125
+ def error_hook[F: Hookable](exc: ExceptionTypes, /, *routes: str) -> Callable[[F], F]: ...
126
+
127
+
128
+ @overload
129
+ def error_hook[F: Hookable](*routes: str, exc: ExceptionTypes = ...) -> Callable[[F], F]: ...
130
+
131
+
132
+ def error_hook(*args: Any, exc: ExceptionTypes | None = None) -> Any:
133
+ match args:
134
+ case (target,) if not isinstance(target, (str, tuple)) and not _is_exception_type(target):
135
+ return _hook(target, _error_info(exc, ()))
136
+ case (first, *routes) if not isinstance(first, str):
137
+ if exc is not None:
138
+ raise DecoratorUsageError("an error hook takes its exceptions first or as `exc=`, not both")
139
+
140
+ return _decorator(_error_info(first, tuple(routes)))
141
+ case routes:
142
+ return _decorator(_error_info(exc, routes))
143
+
144
+
145
+ def lifespan[F: classmethod[Any, ..., Any]](func: F, /) -> F:
146
+ """A classmethod async generator run with the app: `yield` once, between startup and shutdown."""
147
+
148
+ if not inspect.isasyncgenfunction(getattr(func, "__func__", None)):
149
+ raise DecoratorUsageError(f"lifespan() decorates an async generator classmethod, got {func!r}")
150
+
151
+ return _hook(func, LifespanHookInfo()) # ty: ignore[invalid-explicit-return]
152
+
153
+
154
+ __all__ = [
155
+ "error_hook",
156
+ "lifespan",
157
+ "request_hook",
158
+ ]
@@ -0,0 +1,84 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+ from typing import Any, final
6
+
7
+ from fastapi_cls_view.docs import Documented
8
+ from fastapi_cls_view.types import (
9
+ Hookable,
10
+ HookMode,
11
+ ResponseDocs,
12
+ )
13
+
14
+
15
+ # one info per decorator, as pydantic's `FieldValidatorDecoratorInfo` and the like
16
+ @final
17
+ @dataclass(frozen=True, slots=True)
18
+ class RequestHookInfo:
19
+ mode: HookMode
20
+ routes: tuple[str, ...] # empty: every route
21
+
22
+
23
+ @final
24
+ @dataclass(frozen=True, slots=True)
25
+ class ErrorHookInfo:
26
+ routes: tuple[str, ...]
27
+ exceptions: tuple[type[BaseException], ...]
28
+ excluded: tuple[type[BaseException], ...] = ()
29
+
30
+ def distance(self, exc: BaseException, /) -> int | None:
31
+ if isinstance(exc, self.excluded):
32
+ return None
33
+
34
+ mro = type(exc).__mro__
35
+ return min((mro.index(tp) for tp in self.exceptions if tp in mro), default=None)
36
+
37
+
38
+ @final
39
+ @dataclass(frozen=True, slots=True)
40
+ class LifespanHookInfo:
41
+ pass # runs with the app, not on a route
42
+
43
+
44
+ type HookInfo = RequestHookInfo | ErrorHookInfo | LifespanHookInfo
45
+
46
+
47
+ @final
48
+ @dataclass(frozen=True, slots=True)
49
+ class ViewHook[I: HookInfo](Documented):
50
+ name: str
51
+ wrapped: Hookable
52
+ info: I
53
+ docs: ResponseDocs = ()
54
+
55
+ @property
56
+ def func(self) -> Callable[..., Any]:
57
+ match self.wrapped:
58
+ case classmethod(__func__=func):
59
+ return func
60
+ case func:
61
+ return func
62
+
63
+ def applies_to(self, route: str, /) -> bool:
64
+ match self.info:
65
+ case LifespanHookInfo():
66
+ return False
67
+ case info:
68
+ return not info.routes or route in info.routes
69
+
70
+ @property
71
+ def on_class(self) -> bool:
72
+ return isinstance(self.wrapped, classmethod)
73
+
74
+ def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> Any:
75
+ return self.wrapped.__get__(instance, owner)
76
+
77
+
78
+ __all__ = [
79
+ "ErrorHookInfo",
80
+ "HookInfo",
81
+ "LifespanHookInfo",
82
+ "RequestHookInfo",
83
+ "ViewHook",
84
+ ]
@@ -0,0 +1,139 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import AsyncGenerator, Callable, Generator
5
+ from contextlib import aclosing, closing
6
+ from functools import WRAPPER_ASSIGNMENTS, partial
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from fastapi_injected.ext import is_async_callable
10
+ from starlette.concurrency import iterate_in_threadpool
11
+
12
+ from fastapi_cls_view._internal.routes.binding import run, split_view
13
+ from fastapi_cls_view.errors import StreamHookError
14
+
15
+ if TYPE_CHECKING:
16
+ from fastapi_cls_view.types import RequestHook
17
+
18
+
19
+ def is_stream(func: Callable[..., Any], /) -> bool:
20
+ return inspect.isgeneratorfunction(func) or inspect.isasyncgenfunction(func)
21
+
22
+
23
+ def _map(hook: Callable[..., Any], view: Any, items: Any, /) -> Generator[Any]:
24
+ with closing(items):
25
+ for item in items:
26
+ yield hook(view, item)
27
+
28
+
29
+ async def _async_map(hook: Callable[..., Any], view: Any, items: Any, /) -> AsyncGenerator[Any]:
30
+ async with aclosing(items):
31
+ async for item in items:
32
+ yield await run(hook, view, item)
33
+
34
+
35
+ def _returning(value: Any, /) -> Any:
36
+ return value
37
+
38
+
39
+ def _makes_stream_async(hook: RequestHook, /) -> bool:
40
+ match hook.info.mode:
41
+ case "after":
42
+ return is_async_callable(hook.func)
43
+ case _:
44
+ return inspect.isasyncgenfunction(hook.func)
45
+
46
+
47
+ def _check_stream_wrap(hook: RequestHook, is_async: bool, /) -> None:
48
+ if hook.info.mode != "wrap":
49
+ return
50
+
51
+ if is_async and not inspect.isasyncgenfunction(hook.func):
52
+ raise StreamHookError(hook.func, "an async")
53
+
54
+ if not is_async and not inspect.isgeneratorfunction(hook.func):
55
+ raise StreamHookError(hook.func, "a")
56
+
57
+
58
+ def _named_after[F: Callable[..., Any]](wrapper: F, func: Callable[..., Any], /) -> F:
59
+ # not `wraps`: FastAPI looks through `__wrapped__` to tell how to stream, and the route may be of another kind
60
+ for attr in WRAPPER_ASSIGNMENTS:
61
+ setattr(wrapper, attr, getattr(func, attr))
62
+
63
+ return wrapper
64
+
65
+
66
+ def _wrap_items(hooks: list[RequestHook], view: Any, items: Any, is_async: bool, made: list[Any], /) -> Any:
67
+ for hook in hooks:
68
+ if hook.info.mode == "wrap":
69
+ items = hook.func(view, partial(_returning, items))
70
+ elif is_async:
71
+ items = _async_map(hook.func, view, items)
72
+ else:
73
+ items = _map(hook.func, view, items)
74
+
75
+ made.append(items)
76
+
77
+ return items
78
+
79
+
80
+ async def _aclose_all(made: list[Any], /) -> None:
81
+ # a `wrap` hook iterates what it was handed, `async for` never closes it: the outermost first
82
+ for items in reversed(made):
83
+ if (aclose := getattr(items, "aclose", None)) is not None:
84
+ await aclose()
85
+ elif (close := getattr(items, "close", None)) is not None:
86
+ close()
87
+
88
+
89
+ def _close_all(made: list[Any], /) -> None:
90
+ for items in reversed(made):
91
+ if (close := getattr(items, "close", None)) is not None:
92
+ close()
93
+
94
+
95
+ def streamed(func: Callable[..., Any], self_name: str, hooks: list[RequestHook], /) -> Any:
96
+ is_async = inspect.isasyncgenfunction(func) or any(_makes_stream_async(hook) for hook in hooks)
97
+
98
+ for hook in hooks:
99
+ _check_stream_wrap(hook, is_async)
100
+
101
+ def stream(view: Any, args: tuple[Any, ...], kwargs: dict[str, Any], made: list[Any]) -> Any:
102
+ items: Any = func(view, *args, **kwargs)
103
+ made.append(items)
104
+
105
+ if is_async and inspect.isgeneratorfunction(func):
106
+ items = iterate_in_threadpool(items)
107
+
108
+ return _wrap_items(hooks, view, items, is_async, made)
109
+
110
+ if is_async:
111
+
112
+ async def async_call(*args: Any, **kwargs: Any) -> AsyncGenerator[Any]:
113
+ view, args = split_view(self_name, args, kwargs)
114
+ made: list[Any] = []
115
+
116
+ try:
117
+ async for item in stream(view, args, kwargs, made):
118
+ yield item
119
+ finally:
120
+ await _aclose_all(made)
121
+
122
+ return _named_after(async_call, func)
123
+
124
+ def call(*args: Any, **kwargs: Any) -> Generator[Any]:
125
+ view, args = split_view(self_name, args, kwargs)
126
+ made: list[Any] = []
127
+
128
+ try:
129
+ yield from stream(view, args, kwargs, made)
130
+ finally:
131
+ _close_all(made)
132
+
133
+ return _named_after(call, func)
134
+
135
+
136
+ __all__ = [
137
+ "is_stream",
138
+ "streamed",
139
+ ]