|
15 | 15 |
|
16 | 16 | import click |
17 | 17 | from pydantic import BaseModel, TypeAdapter |
| 18 | +from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema |
| 19 | +from pydantic.json_schema import JsonSchemaValue |
| 20 | +from pydantic_core import core_schema |
18 | 21 |
|
19 | 22 | from bo4e import ZusatzAttribut |
20 | 23 |
|
|
34 | 37 | PARSABLE_CLASS_TYPE = type[BaseModel] | type[Enum] |
35 | 38 |
|
36 | 39 |
|
| 40 | +class GenerateJsonSchema(_GenerateJsonSchema): |
| 41 | + """ |
| 42 | + This class is a copy of pydantic.json_schema.GenerateJsonSchema with the only difference that the |
| 43 | + decimal_schema method is overwritten to generate a JSON schema that can be used by the |
| 44 | + BO4E-Python-Generator (https://github.com/bo4e/BO4E-Python-Generator). |
| 45 | + """ |
| 46 | + |
| 47 | + def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue: |
| 48 | + """ |
| 49 | + Generates a JSON schema that matches a decimal value. |
| 50 | + The output format is changed to work well with BO4E-Python-Generator. |
| 51 | + """ |
| 52 | + json_schema = self.str_schema(core_schema.str_schema()) |
| 53 | + if self.mode == "validation": |
| 54 | + json_schema["format"] = "decimal" |
| 55 | + return json_schema |
| 56 | + |
| 57 | + |
37 | 58 | def delete_json_schemas(packages: list[str]) -> None: |
38 | 59 | """delete all json schemas""" |
39 | 60 | for pkg in packages: |
@@ -84,9 +105,9 @@ def get_schema_json_dict(cls: Any) -> dict[str, Any]: |
84 | 105 | Get the json schema for a class |
85 | 106 | """ |
86 | 107 | if issubclass(cls, BaseModel): |
87 | | - schema_json_dict = cls.model_json_schema() |
| 108 | + schema_json_dict = cls.model_json_schema(schema_generator=GenerateJsonSchema) |
88 | 109 | elif issubclass(cls, Enum): |
89 | | - schema_json_dict = TypeAdapter(cls).json_schema() |
| 110 | + schema_json_dict = TypeAdapter(cls).json_schema(schema_generator=GenerateJsonSchema) |
90 | 111 | else: |
91 | 112 | raise ValueError(f"Class {cls} is neither a pydantic BaseModel nor an enum.") |
92 | 113 | if "$defs" in schema_json_dict: |
|
0 commit comments