Coverage for faststream/_internal/fastapi/get_dependant.py: 91%

37 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1import inspect 

2from collections.abc import Callable, Iterable 

3from dataclasses import fields 

4from typing import TYPE_CHECKING, Annotated, Any, cast, get_args, get_origin 

5 

6from fast_depends.library.serializer import OptionItem 

7from fast_depends.utils import get_typed_annotation 

8from fastapi import params 

9from fastapi.dependencies.models import Dependant 

10from fastapi.dependencies.utils import ( 

11 get_dependant, 

12 get_parameterless_sub_dependant, 

13 get_typed_signature, 

14) 

15from pydantic import Field, create_model 

16from pydantic.fields import FieldInfo 

17 

18from faststream._internal._compat import PYDANTIC_V2, PydanticUndefined 

19 

20if TYPE_CHECKING: 

21 from fastapi.dependencies import models 

22 from pydantic.fields import ModelField # type: ignore[attr-defined] 

23 

24 

25class _FastStreamDependant(Dependant): 

26 """FastAPI dependant extended with fields required by FastStream.""" 

27 

28 __slots__ = ("custom_fields", "flat_params", "model") 

29 

30 model: type[Any] 

31 custom_fields: dict[str, Any] 

32 flat_params: list[OptionItem] 

33 

34 

35def _extend_fastapi_dependant(dependant: Dependant) -> _FastStreamDependant: 

36 """Copy a native FastAPI dependant into an extensible subclass.""" 

37 return _FastStreamDependant(**{ 

38 field.name: getattr(dependant, field.name) 

39 for field in fields(dependant) 

40 if field.init 

41 }) 

42 

43 

44def get_fastapi_dependant( 

45 orig_call: Callable[..., Any], 

46 dependencies: Iterable["params.Depends"], 

47) -> Any: 

48 """Generate FastStream-Compatible FastAPI Dependant object.""" 

49 dependent = get_fastapi_native_dependant( 

50 orig_call=orig_call, 

51 dependencies=dependencies, 

52 ) 

53 

54 return _patch_fastapi_dependent(dependent) 

55 

56 

57def get_fastapi_native_dependant( 

58 orig_call: Callable[..., Any], 

59 dependencies: Iterable["params.Depends"], 

60) -> Any: 

61 """Generate native FastAPI Dependant.""" 

62 dependent = get_dependant( 

63 path="", 

64 call=orig_call, 

65 ) 

66 

67 for depends in list(dependencies)[::-1]: 

68 dependent.dependencies.insert( 

69 0, 

70 get_parameterless_sub_dependant(depends=depends, path=""), 

71 ) 

72 

73 return dependent 

74 

75 

76def _patch_fastapi_dependent(dependant: "models.Dependant") -> "models.Dependant": 

77 """Patch FastAPI by adding fields for AsyncAPI schema generation.""" 

78 dependant = _extend_fastapi_dependant(dependant) 

79 params = dependant.query_params + dependant.body_params 

80 

81 for d in dependant.dependencies: 

82 params.extend(d.query_params + d.body_params) 

83 

84 params_unique = {} 

85 

86 call = dependant.call 

87 if is_faststream_decorated(call): 

88 call = getattr(call, "__wrapped__", call) 

89 globalns = getattr(call, "__globals__", {}) 

90 

91 for p in params: 

92 if p.name not in params_unique: 

93 info: Any = p.field_info if PYDANTIC_V2 else p 

94 

95 field_data = { 

96 "default": ... if info.default is PydanticUndefined else info.default, 

97 "default_factory": info.default_factory, 

98 "alias": info.alias, 

99 } 

100 

101 if PYDANTIC_V2: 101 ↛ 127line 101 didn't jump to line 127 because the condition on line 101 was always true

102 info = cast("FieldInfo", info) 

103 

104 field_data.update( 

105 { 

106 "title": info.title, 

107 "alias_priority": info.alias_priority, 

108 "validation_alias": info.validation_alias, 

109 "serialization_alias": info.serialization_alias, 

110 "description": info.description, 

111 "discriminator": info.discriminator, 

112 "examples": info.examples, 

113 "exclude": info.exclude, 

114 "json_schema_extra": info.json_schema_extra, 

115 }, 

116 ) 

117 

118 f = next( 

119 filter( 

120 lambda x: isinstance(x, FieldInfo), 

121 p.field_info.metadata or (), 

122 ), 

123 Field(**field_data), # type: ignore[pydantic-field,unused-ignore] 

124 ) 

125 

126 else: 

127 info = cast("ModelField", info) 

128 

129 field_data.update( 

130 { 

131 "title": info.field_info.title, 

132 "description": info.field_info.description, 

133 "discriminator": info.field_info.discriminator, 

134 "exclude": info.field_info.exclude, 

135 "gt": info.field_info.gt, 

136 "ge": info.field_info.ge, 

137 "lt": info.field_info.lt, 

138 "le": info.field_info.le, 

139 }, 

140 ) 

141 f = Field(**field_data) # type: ignore[pydantic-field,unused-ignore] 

142 

143 params_unique[p.name] = ( 

144 get_typed_annotation(info.annotation, globalns, {}), 

145 f, 

146 ) 

147 

148 dependant.model = create_model( 

149 getattr(call, "__name__", type(call).__name__), 

150 ) 

151 

152 dependant.custom_fields = {} 

153 dependant.flat_params = [ 

154 OptionItem(field_name=name, field_type=type_, default_value=default) 

155 for name, (type_, default) in params_unique.items() 

156 ] 

157 

158 return dependant 

159 

160 

161def has_forbidden_types( 

162 orig_call: Callable[..., Any], 

163 forbidden_types: tuple[Any, ...], 

164) -> set[Any]: 

165 """Check if faststream.Depends is used in the handler.""" 

166 endpoint_signature = get_typed_signature(orig_call) 

167 signature_params = endpoint_signature.parameters 

168 

169 founded_types = set() 

170 

171 for param in signature_params.values(): 

172 ann = param.annotation 

173 

174 founded_buffer = set() 

175 has_fastapi_depends = False 

176 if ann is not inspect.Signature.empty and get_origin(ann) is Annotated: 

177 annotated_args = get_args(ann) 

178 

179 for arg in annotated_args[1:]: 

180 if isinstance(arg, params.Depends): 

181 has_fastapi_depends = True 

182 continue 

183 

184 for t in forbidden_types: 

185 if isinstance(arg, t): 

186 founded_buffer.add(t) 

187 

188 if isinstance(param.default, params.Depends): 

189 has_fastapi_depends = True 

190 continue 

191 

192 for t in forbidden_types: 

193 if isinstance(param.default, t): 

194 founded_buffer.add(t) 

195 

196 if not has_fastapi_depends: 

197 founded_types |= founded_buffer 

198 

199 return founded_types 

200 

201 

202FASTSTREAM_FASTAPI_PLUGIN_DECORATOR_MARKER = "__faststream_consumer__" 

203 

204 

205def is_faststream_decorated(func: object) -> bool: 

206 return getattr(func, FASTSTREAM_FASTAPI_PLUGIN_DECORATOR_MARKER, False) 

207 

208 

209def mark_faststream_decorated(func: object) -> None: 

210 setattr(func, FASTSTREAM_FASTAPI_PLUGIN_DECORATOR_MARKER, True)