|
| 1 | +"""A FastAPI dependency that provides a Kafkit PydanticSchemaManager |
| 2 | +for serializing Pydantic models into Avro. |
| 3 | +""" |
| 4 | + |
| 5 | +from collections.abc import Iterable |
| 6 | +from typing import Type |
| 7 | + |
| 8 | +from dataclasses_avroschema.avrodantic import AvroBaseModel |
| 9 | +from httpx import AsyncClient |
| 10 | + |
| 11 | +from kafkit.registry import manager # this is patched in tests |
| 12 | +from kafkit.registry.httpx import RegistryApi |
| 13 | + |
| 14 | +__all__ = [ |
| 15 | + "pydantic_schema_manager_dependency", |
| 16 | + "PydanticSchemaManagerDependency", |
| 17 | +] |
| 18 | + |
| 19 | + |
| 20 | +class PydanticSchemaManagerDependency: |
| 21 | + """A FastAPI dependency that provides a Kafkit PydanticSchemaManager |
| 22 | + for serializing Pydantic models into Avro. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self) -> None: |
| 26 | + self._schema_manager: manager.PydanticSchemaManager | None = None |
| 27 | + |
| 28 | + async def initialize( |
| 29 | + self, |
| 30 | + *, |
| 31 | + http_client: AsyncClient, |
| 32 | + registry_url: str, |
| 33 | + models: Iterable[Type[AvroBaseModel]], |
| 34 | + suffix: str = "", |
| 35 | + compatibility: str = "FORWARD", |
| 36 | + ) -> None: |
| 37 | + """Initialize the dependency (call during FastAPI startup). |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + http_client |
| 42 | + The httpx AsyncClient instance to use for HTTP requests. |
| 43 | + registry_url |
| 44 | + The URL of the Schema Registry. |
| 45 | + models |
| 46 | + The Pydantic models to register. |
| 47 | + suffix |
| 48 | + A suffix that is added to the schema name (and thus subject name), |
| 49 | + for example ``_dev1``. |
| 50 | + compatibility |
| 51 | + The compatibility level to use when registering the schemas. |
| 52 | + """ |
| 53 | + registry_api = RegistryApi(http_client=http_client, url=registry_url) |
| 54 | + self._schema_manager = manager.PydanticSchemaManager( |
| 55 | + registry=registry_api, suffix=suffix |
| 56 | + ) |
| 57 | + |
| 58 | + await self._schema_manager.register_models( |
| 59 | + models, compatibility=compatibility |
| 60 | + ) |
| 61 | + |
| 62 | + async def __call__(self) -> manager.PydanticSchemaManager: |
| 63 | + """Get the dependency (call during FastAPI request handling).""" |
| 64 | + if self._schema_manager is None: |
| 65 | + raise RuntimeError("Dependency not initialized") |
| 66 | + return self._schema_manager |
| 67 | + |
| 68 | + |
| 69 | +pydantic_schema_manager_dependency = PydanticSchemaManagerDependency() |
| 70 | +"""The FastAPI dependency callable that provides a Kafkit PydanticSchemaManager |
| 71 | +instance for serializing Pydantic models into Avro. |
| 72 | +""" |
0 commit comments