| 1 |
from inspect import Parameter, Signature |
| 2 |
from typing import Any, Dict, Tuple |
| 3 |
|
| 4 |
from litestar import Litestar, get |
| 5 |
from litestar.di import NamedDependency, Provide |
| 6 |
from litestar.params import FromQuery |
| 7 |
from litestar.plugins import DIPlugin |
| 8 |
|
| 9 |
|
| 10 |
class MyBaseType: |
| 11 |
def __init__(self, param): |
| 12 |
self.param = param |
| 13 |
|
| 14 |
|
| 15 |
class MyDIPlugin(DIPlugin): |
| 16 |
def has_typed_init(self, type_: Any) -> bool: |
| 17 |
return issubclass(type_, MyBaseType) |
| 18 |
|
| 19 |
def get_typed_init(self, type_: Any) -> Tuple[Signature, Dict[str, Any]]: |
| 20 |
signature = Signature([Parameter(name="param", kind=Parameter.POSITIONAL_OR_KEYWORD)]) |
| 21 |
annotations = {"param": FromQuery[str]} |
| 22 |
return signature, annotations |
| 23 |
|
| 24 |
|
| 25 |
@get("/", dependencies={"injected": Provide(MyBaseType, sync_to_thread=False)}) |
| 26 |
async def handler(injected: NamedDependency[MyBaseType]) -> str: |
| 27 |
return injected.param |
| 28 |
|
| 29 |
|
| 30 |
app = Litestar(route_handlers=[handler], plugins=[MyDIPlugin()]) |
| 31 |
|
| 32 |
# run: /?param=hello |