Skip to content

Commit 4cccb9c

Browse files
committed
create dependencies helper
1 parent e233b5a commit 4cccb9c

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import inspect
2+
from typing import (
3+
Any,
4+
Awaitable,
5+
Callable,
6+
TypeVar,
7+
Union,
8+
)
9+
10+
from fastapi import Request
11+
from fastapi.dependencies.models import Dependant
12+
from fastapi.dependencies.utils import (
13+
get_dependant,
14+
solve_dependencies,
15+
)
16+
from fastapi.exceptions import RequestValidationError
17+
18+
ReturnType = TypeVar("ReturnType")
19+
FuncReturnType = Union[Awaitable[ReturnType], ReturnType]
20+
21+
22+
class DependencyHelper:
23+
"""
24+
DependencyHelper for resolving dependencies.
25+
26+
Use this helper to run a func with some FastAPI Dependencies
27+
"""
28+
29+
def __init__(self, request: Request):
30+
self.request = request
31+
32+
async def solve_dependencies_and_run(self, dependant: Dependant) -> ReturnType:
33+
body_data = await self.request.body() or None
34+
body = body_data and (await self.request.json())
35+
values, errors, *_ = await solve_dependencies( # WPS110
36+
request=self.request,
37+
dependant=dependant,
38+
body=body,
39+
)
40+
41+
if errors:
42+
raise RequestValidationError(errors, body=body)
43+
44+
orig_func: Callable[..., FuncReturnType[Any]] = dependant.call # type: ignore
45+
if inspect.iscoroutinefunction(orig_func):
46+
function_call_result = await orig_func(**values)
47+
else:
48+
function_call_result = orig_func(**values)
49+
50+
return function_call_result
51+
52+
async def run(self, func: Callable[..., FuncReturnType[Any]]) -> ReturnType:
53+
dependant = get_dependant(
54+
path=self.request.url.path,
55+
call=func,
56+
)
57+
58+
return await self.solve_dependencies_and_run(dependant)

0 commit comments

Comments
 (0)