fastapi-app-builder 0.1.0b1__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.
- fastapi_app_builder/__init__.py +65 -0
- fastapi_app_builder/builder.py +360 -0
- fastapi_app_builder/container.py +379 -0
- fastapi_app_builder/exceptions.py +42 -0
- fastapi_app_builder/installers/__init__.py +7 -0
- fastapi_app_builder/installers/cors.py +39 -0
- fastapi_app_builder/installers/database.py +102 -0
- fastapi_app_builder/lifetime.py +9 -0
- fastapi_app_builder/middleware.py +38 -0
- fastapi_app_builder/patch.py +201 -0
- fastapi_app_builder/py.typed +0 -0
- fastapi_app_builder/resolver.py +76 -0
- fastapi_app_builder/router.py +511 -0
- fastapi_app_builder/validation.py +35 -0
- fastapi_app_builder/wrapper.py +86 -0
- fastapi_app_builder-0.1.0b1.dist-info/METADATA +364 -0
- fastapi_app_builder-0.1.0b1.dist-info/RECORD +19 -0
- fastapi_app_builder-0.1.0b1.dist-info/WHEEL +4 -0
- fastapi_app_builder-0.1.0b1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TypeVar, get_type_hints
|
|
7
|
+
|
|
8
|
+
from .exceptions import (
|
|
9
|
+
CircularDependencyError,
|
|
10
|
+
ScopeNotFoundError,
|
|
11
|
+
ServiceNotRegisteredError,
|
|
12
|
+
)
|
|
13
|
+
from .lifetime import Lifetime
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
# Context variable for request-scoped services
|
|
18
|
+
_request_scope: ContextVar[dict[type, object] | None] = ContextVar(
|
|
19
|
+
"request_scope", default=None
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def get_request_scope() -> ContextVar[dict[type, object] | None]:
|
|
24
|
+
"""Get the request scope context variable."""
|
|
25
|
+
return _request_scope
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ServiceDescriptor:
|
|
30
|
+
"""Describes a registered service."""
|
|
31
|
+
|
|
32
|
+
interface: type
|
|
33
|
+
implementation: type | None
|
|
34
|
+
factory: Callable[[], object] | None
|
|
35
|
+
lifetime: Lifetime
|
|
36
|
+
dispose: Callable[[object], None] | None = None # Cleanup function
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Services:
|
|
40
|
+
"""Dependency injection container."""
|
|
41
|
+
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
self._registrations: dict[type, ServiceDescriptor] = {}
|
|
44
|
+
self._singletons: dict[type, object] = {}
|
|
45
|
+
self._resolution_stack: list[type] = []
|
|
46
|
+
|
|
47
|
+
# Registration methods
|
|
48
|
+
def add_singleton(
|
|
49
|
+
self,
|
|
50
|
+
interface: type[T],
|
|
51
|
+
implementation: type[T] | None = None,
|
|
52
|
+
) -> Services:
|
|
53
|
+
"""Register a singleton service (one instance per application)."""
|
|
54
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
55
|
+
interface=interface,
|
|
56
|
+
implementation=implementation,
|
|
57
|
+
factory=None,
|
|
58
|
+
lifetime=Lifetime.SINGLETON,
|
|
59
|
+
)
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
def add_scoped(
|
|
63
|
+
self,
|
|
64
|
+
interface: type[T],
|
|
65
|
+
implementation: type[T] | None = None,
|
|
66
|
+
) -> Services:
|
|
67
|
+
"""Register a scoped service (one instance per request)."""
|
|
68
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
69
|
+
interface=interface,
|
|
70
|
+
implementation=implementation,
|
|
71
|
+
factory=None,
|
|
72
|
+
lifetime=Lifetime.SCOPED,
|
|
73
|
+
)
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
def add_transient(
|
|
77
|
+
self,
|
|
78
|
+
interface: type[T],
|
|
79
|
+
implementation: type[T] | None = None,
|
|
80
|
+
) -> Services:
|
|
81
|
+
"""Register a transient service (new instance every time)."""
|
|
82
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
83
|
+
interface=interface,
|
|
84
|
+
implementation=implementation,
|
|
85
|
+
factory=None,
|
|
86
|
+
lifetime=Lifetime.TRANSIENT,
|
|
87
|
+
)
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
def add_singleton_factory(
|
|
91
|
+
self,
|
|
92
|
+
interface: type[T],
|
|
93
|
+
factory: Callable[[], T],
|
|
94
|
+
) -> Services:
|
|
95
|
+
"""Register a singleton service using a factory function."""
|
|
96
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
97
|
+
interface=interface,
|
|
98
|
+
implementation=None,
|
|
99
|
+
factory=factory,
|
|
100
|
+
lifetime=Lifetime.SINGLETON,
|
|
101
|
+
)
|
|
102
|
+
return self
|
|
103
|
+
|
|
104
|
+
def add_scoped_factory(
|
|
105
|
+
self,
|
|
106
|
+
interface: type[T],
|
|
107
|
+
factory: Callable[[], T],
|
|
108
|
+
dispose: Callable[[T], None] | None = None,
|
|
109
|
+
) -> Services:
|
|
110
|
+
"""Register a scoped service using a factory function.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
interface: The service type/interface
|
|
114
|
+
factory: Function that creates the service instance
|
|
115
|
+
dispose: Optional cleanup function called when request ends
|
|
116
|
+
|
|
117
|
+
Example:
|
|
118
|
+
# DB session with automatic cleanup
|
|
119
|
+
builder.services.add_scoped_factory(
|
|
120
|
+
Session,
|
|
121
|
+
factory=SessionLocal,
|
|
122
|
+
dispose=lambda s: s.close()
|
|
123
|
+
)
|
|
124
|
+
"""
|
|
125
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
126
|
+
interface=interface,
|
|
127
|
+
implementation=None,
|
|
128
|
+
factory=factory,
|
|
129
|
+
lifetime=Lifetime.SCOPED,
|
|
130
|
+
dispose=dispose, # type: ignore[arg-type]
|
|
131
|
+
)
|
|
132
|
+
return self
|
|
133
|
+
|
|
134
|
+
def add_transient_factory(
|
|
135
|
+
self,
|
|
136
|
+
interface: type[T],
|
|
137
|
+
factory: Callable[[], T],
|
|
138
|
+
) -> Services:
|
|
139
|
+
"""Register a transient service using a factory function."""
|
|
140
|
+
self._registrations[interface] = ServiceDescriptor(
|
|
141
|
+
interface=interface,
|
|
142
|
+
implementation=None,
|
|
143
|
+
factory=factory,
|
|
144
|
+
lifetime=Lifetime.TRANSIENT,
|
|
145
|
+
)
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
def install(self, installer: Callable[[Services], None]) -> Services:
|
|
149
|
+
"""Apply an installer function to register services.
|
|
150
|
+
|
|
151
|
+
Installers are functions that take a Services container and register
|
|
152
|
+
services. This allows organizing registrations into reusable modules.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
installer: Function that registers services
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
Self for method chaining
|
|
159
|
+
|
|
160
|
+
Example:
|
|
161
|
+
# repositories.py
|
|
162
|
+
def install_repositories(services: Services) -> None:
|
|
163
|
+
services.add_scoped(IUserRepository, UserRepository)
|
|
164
|
+
services.add_scoped(IProductRepository, ProductRepository)
|
|
165
|
+
|
|
166
|
+
# services.py
|
|
167
|
+
def install_services(services: Services) -> None:
|
|
168
|
+
services.add_scoped(IUserService, UserService)
|
|
169
|
+
services.add_scoped(IOrderService, OrderService)
|
|
170
|
+
|
|
171
|
+
# main.py
|
|
172
|
+
builder = AppBuilder()
|
|
173
|
+
builder.services.install(install_repositories)
|
|
174
|
+
builder.services.install(install_services)
|
|
175
|
+
"""
|
|
176
|
+
installer(self)
|
|
177
|
+
return self
|
|
178
|
+
|
|
179
|
+
# Resolution
|
|
180
|
+
def is_registered(self, interface: type) -> bool:
|
|
181
|
+
"""Check if a service is registered."""
|
|
182
|
+
return interface in self._registrations
|
|
183
|
+
|
|
184
|
+
def resolve(self, interface: type[T]) -> T:
|
|
185
|
+
"""Resolve a service instance."""
|
|
186
|
+
if not self.is_registered(interface):
|
|
187
|
+
raise ServiceNotRegisteredError(interface)
|
|
188
|
+
|
|
189
|
+
descriptor = self._registrations[interface]
|
|
190
|
+
|
|
191
|
+
match descriptor.lifetime:
|
|
192
|
+
case Lifetime.SINGLETON:
|
|
193
|
+
return self._resolve_singleton(descriptor) # type: ignore[return-value]
|
|
194
|
+
case Lifetime.SCOPED:
|
|
195
|
+
return self._resolve_scoped(descriptor) # type: ignore[return-value]
|
|
196
|
+
case Lifetime.TRANSIENT:
|
|
197
|
+
return self._resolve_transient(descriptor) # type: ignore[return-value]
|
|
198
|
+
|
|
199
|
+
raise ValueError(f"Unknown lifetime: {descriptor.lifetime}")
|
|
200
|
+
|
|
201
|
+
def _resolve_singleton(self, descriptor: ServiceDescriptor) -> object:
|
|
202
|
+
"""Resolve a singleton service."""
|
|
203
|
+
if descriptor.interface not in self._singletons:
|
|
204
|
+
instance = self._create_instance(descriptor)
|
|
205
|
+
self._singletons[descriptor.interface] = instance
|
|
206
|
+
return self._singletons[descriptor.interface]
|
|
207
|
+
|
|
208
|
+
def _resolve_scoped(self, descriptor: ServiceDescriptor) -> object:
|
|
209
|
+
"""Resolve a scoped service."""
|
|
210
|
+
scope = _request_scope.get()
|
|
211
|
+
if scope is None:
|
|
212
|
+
raise ScopeNotFoundError()
|
|
213
|
+
|
|
214
|
+
if descriptor.interface not in scope:
|
|
215
|
+
instance = self._create_instance(descriptor)
|
|
216
|
+
scope[descriptor.interface] = instance
|
|
217
|
+
return scope[descriptor.interface]
|
|
218
|
+
|
|
219
|
+
def _resolve_transient(self, descriptor: ServiceDescriptor) -> object:
|
|
220
|
+
"""Resolve a transient service."""
|
|
221
|
+
return self._create_instance(descriptor)
|
|
222
|
+
|
|
223
|
+
def _create_instance(self, descriptor: ServiceDescriptor) -> object:
|
|
224
|
+
"""Create a new instance of a service."""
|
|
225
|
+
# Check for circular dependencies
|
|
226
|
+
if descriptor.interface in self._resolution_stack:
|
|
227
|
+
cycle = self._resolution_stack + [descriptor.interface]
|
|
228
|
+
raise CircularDependencyError(cycle)
|
|
229
|
+
|
|
230
|
+
self._resolution_stack.append(descriptor.interface)
|
|
231
|
+
try:
|
|
232
|
+
if descriptor.factory:
|
|
233
|
+
return descriptor.factory()
|
|
234
|
+
|
|
235
|
+
impl = descriptor.implementation or descriptor.interface
|
|
236
|
+
|
|
237
|
+
# Get constructor type hints
|
|
238
|
+
try:
|
|
239
|
+
hints = get_type_hints(impl.__init__) # type: ignore[misc]
|
|
240
|
+
except Exception:
|
|
241
|
+
hints = {}
|
|
242
|
+
|
|
243
|
+
# Resolve constructor dependencies
|
|
244
|
+
kwargs: dict[str, object] = {}
|
|
245
|
+
for name, hint in hints.items():
|
|
246
|
+
if name == "return":
|
|
247
|
+
continue
|
|
248
|
+
if self.is_registered(hint):
|
|
249
|
+
kwargs[name] = self.resolve(hint)
|
|
250
|
+
|
|
251
|
+
return impl(**kwargs)
|
|
252
|
+
finally:
|
|
253
|
+
self._resolution_stack.pop()
|
|
254
|
+
|
|
255
|
+
# Validation
|
|
256
|
+
def validate(self) -> list[str]:
|
|
257
|
+
"""Validate all registrations and return list of errors."""
|
|
258
|
+
errors: list[str] = []
|
|
259
|
+
|
|
260
|
+
for _interface, descriptor in self._registrations.items():
|
|
261
|
+
if descriptor.factory:
|
|
262
|
+
# Can't validate factory dependencies
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
impl = descriptor.implementation or descriptor.interface
|
|
266
|
+
errors.extend(self._validate_dependencies(impl, chain=[]))
|
|
267
|
+
|
|
268
|
+
return errors
|
|
269
|
+
|
|
270
|
+
def validate_endpoint(self, func: Callable[..., object]) -> list[str]:
|
|
271
|
+
"""Validate that all injected dependencies for an endpoint are available."""
|
|
272
|
+
errors: list[str] = []
|
|
273
|
+
|
|
274
|
+
try:
|
|
275
|
+
hints = get_type_hints(func)
|
|
276
|
+
except Exception:
|
|
277
|
+
return errors
|
|
278
|
+
|
|
279
|
+
for name, hint in hints.items():
|
|
280
|
+
if name == "return":
|
|
281
|
+
continue
|
|
282
|
+
if self._is_injectable_type(hint) and not self.is_registered(hint):
|
|
283
|
+
errors.append(
|
|
284
|
+
f"Endpoint '{func.__name__}' requires "
|
|
285
|
+
f"'{hint.__name__}' which is not registered"
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
return errors
|
|
289
|
+
|
|
290
|
+
def _validate_dependencies(
|
|
291
|
+
self,
|
|
292
|
+
impl: type,
|
|
293
|
+
chain: list[type],
|
|
294
|
+
) -> list[str]:
|
|
295
|
+
"""Validate dependencies recursively."""
|
|
296
|
+
errors: list[str] = []
|
|
297
|
+
|
|
298
|
+
if impl in chain:
|
|
299
|
+
cycle = " -> ".join(t.__name__ for t in chain + [impl])
|
|
300
|
+
return [f"Circular dependency: {cycle}"]
|
|
301
|
+
|
|
302
|
+
try:
|
|
303
|
+
hints = get_type_hints(impl.__init__) # type: ignore[misc]
|
|
304
|
+
except Exception:
|
|
305
|
+
return errors
|
|
306
|
+
|
|
307
|
+
for name, hint in hints.items():
|
|
308
|
+
if name == "return":
|
|
309
|
+
continue
|
|
310
|
+
if self._is_injectable_type(hint):
|
|
311
|
+
if not self.is_registered(hint):
|
|
312
|
+
errors.append(
|
|
313
|
+
f"Service '{impl.__name__}' requires "
|
|
314
|
+
f"'{hint.__name__}' which is not registered"
|
|
315
|
+
)
|
|
316
|
+
else:
|
|
317
|
+
descriptor = self._registrations[hint]
|
|
318
|
+
if descriptor.factory:
|
|
319
|
+
# Can't validate factory dependencies further
|
|
320
|
+
continue
|
|
321
|
+
dep_impl = descriptor.implementation or hint
|
|
322
|
+
errors.extend(
|
|
323
|
+
self._validate_dependencies(dep_impl, chain + [impl])
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
return errors
|
|
327
|
+
|
|
328
|
+
def _is_injectable_type(self, hint: type) -> bool:
|
|
329
|
+
"""Check if a type hint represents an injectable service."""
|
|
330
|
+
# Skip primitives and common types
|
|
331
|
+
skip = {str, int, float, bool, list, dict, set, tuple, type(None)}
|
|
332
|
+
if hint in skip:
|
|
333
|
+
return False
|
|
334
|
+
|
|
335
|
+
# Skip generic types
|
|
336
|
+
origin = getattr(hint, "__origin__", None)
|
|
337
|
+
if origin is not None:
|
|
338
|
+
return False
|
|
339
|
+
|
|
340
|
+
# Skip Pydantic models (have model_fields attribute)
|
|
341
|
+
if hasattr(hint, "model_fields"):
|
|
342
|
+
return False
|
|
343
|
+
|
|
344
|
+
# Check if it's a class (not a primitive or generic)
|
|
345
|
+
if not isinstance(hint, type):
|
|
346
|
+
return False
|
|
347
|
+
|
|
348
|
+
return True
|
|
349
|
+
|
|
350
|
+
# Scope management
|
|
351
|
+
def dispose_scope(self) -> None:
|
|
352
|
+
"""Dispose all scoped services in the current request.
|
|
353
|
+
|
|
354
|
+
This calls the dispose function for any scoped services that have one.
|
|
355
|
+
Should be called at the end of each request.
|
|
356
|
+
"""
|
|
357
|
+
scope = _request_scope.get()
|
|
358
|
+
if scope is None:
|
|
359
|
+
return
|
|
360
|
+
|
|
361
|
+
for interface, instance in scope.items():
|
|
362
|
+
descriptor = self._registrations.get(interface)
|
|
363
|
+
if descriptor and descriptor.dispose:
|
|
364
|
+
try:
|
|
365
|
+
descriptor.dispose(instance)
|
|
366
|
+
except Exception:
|
|
367
|
+
# Log but don't fail - cleanup should be best-effort
|
|
368
|
+
pass
|
|
369
|
+
|
|
370
|
+
# Testing helpers
|
|
371
|
+
def clear(self) -> None:
|
|
372
|
+
"""Clear all registrations and cached instances."""
|
|
373
|
+
self._registrations.clear()
|
|
374
|
+
self._singletons.clear()
|
|
375
|
+
self._resolution_stack.clear()
|
|
376
|
+
|
|
377
|
+
def get_registration(self, interface: type) -> ServiceDescriptor | None:
|
|
378
|
+
"""Get the registration for a service (for testing/introspection)."""
|
|
379
|
+
return self._registrations.get(interface)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ServiceNotRegisteredError(Exception):
|
|
5
|
+
"""Raised when resolving unregistered service."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, service_type_or_message: type | str) -> None:
|
|
8
|
+
if isinstance(service_type_or_message, str):
|
|
9
|
+
self.service_type = None
|
|
10
|
+
super().__init__(service_type_or_message)
|
|
11
|
+
else:
|
|
12
|
+
self.service_type = service_type_or_message
|
|
13
|
+
name = service_type_or_message.__name__
|
|
14
|
+
super().__init__(f"Service '{name}' is not registered")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CircularDependencyError(Exception):
|
|
18
|
+
"""Raised when circular dependency detected."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, chain: list[type]) -> None:
|
|
21
|
+
self.chain = chain
|
|
22
|
+
cycle = " -> ".join(t.__name__ for t in chain)
|
|
23
|
+
super().__init__(f"Circular dependency detected: {cycle}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ScopeNotFoundError(Exception):
|
|
27
|
+
"""Raised when resolving scoped service outside request."""
|
|
28
|
+
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
super().__init__(
|
|
31
|
+
"Cannot resolve scoped service outside of a request context. "
|
|
32
|
+
"Ensure RequestScopeMiddleware is installed."
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ValidationError(Exception):
|
|
37
|
+
"""Raised when validation fails at build time."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, errors: list[str]) -> None:
|
|
40
|
+
self.errors = errors
|
|
41
|
+
message = "Validation failed:\n" + "\n".join(f" - {e}" for e in errors)
|
|
42
|
+
super().__init__(message)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from ..builder import AppBuilder
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def install_cors(
|
|
11
|
+
origins: list[str],
|
|
12
|
+
allow_credentials: bool = True,
|
|
13
|
+
allow_methods: list[str] | None = None,
|
|
14
|
+
allow_headers: list[str] | None = None,
|
|
15
|
+
) -> Callable[[AppBuilder], None]:
|
|
16
|
+
"""Create a CORS installer.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
origins: List of allowed origins
|
|
20
|
+
allow_credentials: Whether to allow credentials
|
|
21
|
+
allow_methods: List of allowed HTTP methods
|
|
22
|
+
allow_headers: List of allowed headers
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Installer function for CORS
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
builder.install(install_cors(["http://localhost:3000"]))
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def installer(builder: AppBuilder) -> None:
|
|
32
|
+
builder.install_cors(
|
|
33
|
+
origins=origins,
|
|
34
|
+
allow_credentials=allow_credentials,
|
|
35
|
+
allow_methods=allow_methods,
|
|
36
|
+
allow_headers=allow_headers,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
return installer
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Protocol
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from ..builder import AppBuilder
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class IDbSession(Protocol):
|
|
11
|
+
"""Protocol for database session interface."""
|
|
12
|
+
|
|
13
|
+
def commit(self) -> None:
|
|
14
|
+
"""Commit the current transaction."""
|
|
15
|
+
...
|
|
16
|
+
|
|
17
|
+
def rollback(self) -> None:
|
|
18
|
+
"""Rollback the current transaction."""
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
def close(self) -> None:
|
|
22
|
+
"""Close the session."""
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def install_database(connection_string: str) -> Callable[[AppBuilder], None]:
|
|
27
|
+
"""Create a database installer using SQLAlchemy.
|
|
28
|
+
|
|
29
|
+
This installer configures SQLAlchemy with the provided connection string
|
|
30
|
+
and registers a scoped session factory.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
connection_string: Database connection URL
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Installer function for database setup
|
|
37
|
+
|
|
38
|
+
Example:
|
|
39
|
+
builder.install(install_database("postgresql://localhost/mydb"))
|
|
40
|
+
|
|
41
|
+
Note:
|
|
42
|
+
Requires sqlalchemy to be installed:
|
|
43
|
+
`pip install fastapi-injection[sqlalchemy]`
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def installer(builder: AppBuilder) -> None:
|
|
47
|
+
try:
|
|
48
|
+
from sqlalchemy import create_engine # type: ignore[import-not-found]
|
|
49
|
+
from sqlalchemy.orm import ( # type: ignore[import-not-found]
|
|
50
|
+
Session,
|
|
51
|
+
sessionmaker,
|
|
52
|
+
)
|
|
53
|
+
except ImportError as e:
|
|
54
|
+
raise ImportError(
|
|
55
|
+
"SQLAlchemy is required for database support. "
|
|
56
|
+
"Install with: pip install fastapi-injection[sqlalchemy]"
|
|
57
|
+
) from e
|
|
58
|
+
|
|
59
|
+
# Create engine and session factory
|
|
60
|
+
engine = create_engine(connection_string)
|
|
61
|
+
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
|
|
62
|
+
|
|
63
|
+
def create_session() -> Session:
|
|
64
|
+
return session_factory()
|
|
65
|
+
|
|
66
|
+
# Register session as scoped (one per request)
|
|
67
|
+
builder.services.add_scoped_factory(Session, create_session)
|
|
68
|
+
|
|
69
|
+
return installer
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def install_database_with_engine(engine: Any) -> Callable[[AppBuilder], None]:
|
|
73
|
+
"""Create a database installer using an existing SQLAlchemy engine.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
engine: SQLAlchemy Engine instance
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Installer function for database setup
|
|
80
|
+
|
|
81
|
+
Example:
|
|
82
|
+
engine = create_engine("postgresql://localhost/mydb")
|
|
83
|
+
builder.install(install_database_with_engine(engine))
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def installer(builder: AppBuilder) -> None:
|
|
87
|
+
try:
|
|
88
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
89
|
+
except ImportError as e:
|
|
90
|
+
raise ImportError(
|
|
91
|
+
"SQLAlchemy is required for database support. "
|
|
92
|
+
"Install with: pip install fastapi-injection[sqlalchemy]"
|
|
93
|
+
) from e
|
|
94
|
+
|
|
95
|
+
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
|
|
96
|
+
|
|
97
|
+
def create_session() -> Session:
|
|
98
|
+
return session_factory()
|
|
99
|
+
|
|
100
|
+
builder.services.add_scoped_factory(Session, create_session)
|
|
101
|
+
|
|
102
|
+
return installer
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Awaitable, Callable
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
7
|
+
from starlette.requests import Request
|
|
8
|
+
from starlette.responses import Response
|
|
9
|
+
|
|
10
|
+
from .container import Services, get_request_scope
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from starlette.types import ASGIApp
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RequestScopeMiddleware(BaseHTTPMiddleware):
|
|
17
|
+
"""Middleware that manages request-scoped dependency injection."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, app: ASGIApp, services: Services) -> None:
|
|
20
|
+
super().__init__(app)
|
|
21
|
+
self.services = services
|
|
22
|
+
|
|
23
|
+
async def dispatch(
|
|
24
|
+
self,
|
|
25
|
+
request: Request,
|
|
26
|
+
call_next: Callable[[Request], Awaitable[Response]],
|
|
27
|
+
) -> Response:
|
|
28
|
+
"""Handle request with scoped dependency injection context."""
|
|
29
|
+
scope_var = get_request_scope()
|
|
30
|
+
token = scope_var.set({})
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
response: Response = await call_next(request)
|
|
34
|
+
return response
|
|
35
|
+
finally:
|
|
36
|
+
# Dispose scoped services (close DB sessions, etc.)
|
|
37
|
+
self.services.dispose_scope()
|
|
38
|
+
scope_var.reset(token)
|