├── tests ├── __init__.py └── test.py ├── src └── dyntamic │ ├── __init__.py │ └── factory.py ├── README.md ├── pyproject.toml └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/dyntamic/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dyntamic 2 | Generate pydantic models from JSON Schema 3 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling", "pydantic"] 3 | build-backend = "hatchling.build" 4 | [project] 5 | name = "dyntamic" 6 | version = "0.0.2" 7 | authors = [ 8 | { name="RC Max", email="06102011b@gmail.com" }, 9 | ] 10 | description = "A light package to generate pydantic models dynamically from JSON Schema" 11 | readme = "README.md" 12 | requires-python = ">=3.7" 13 | classifiers = [ 14 | "Programming Language :: Python :: 3", 15 | "License :: OSI Approved :: MIT License", 16 | "Operating System :: OS Independent", 17 | ] 18 | 19 | [project.urls] 20 | "Homepage" = "https://github.com/c32168/dyntamic" 21 | "Bug Tracker" = "https://github.com/c32168/dyntamic/issues" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 c32168 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/dyntamic/factory.py: -------------------------------------------------------------------------------- 1 | from typing import Annotated, Union 2 | 3 | import typing 4 | from pydantic import create_model 5 | from pydantic.fields import Field 6 | 7 | Model = typing.TypeVar('Model', bound='BaseModel') 8 | 9 | 10 | class DyntamicFactory: 11 | 12 | TYPES = { 13 | 'string': str, 14 | 'array': list, 15 | 'boolean': bool, 16 | 'integer': int, 17 | 'float': float, 18 | 'number': float, 19 | } 20 | 21 | def __init__(self, 22 | json_schema: dict, 23 | base_model: type[Model] | tuple[type[Model], ...] | None = None, 24 | ref_template: str = "#/$defs/" 25 | ) -> None: 26 | """ 27 | Creates a dynamic pydantic model from a JSONSchema, dumped from and existing Pydantic model elsewhere. 28 | JSONSchema dump must be called with ref_template='{model}' like: 29 | 30 | SomeSampleModel.model_json_schema(ref_template='{model}') 31 | Use: 32 | >> _factory = DyntamicFactory(schema) 33 | >> _factory.make() 34 | >> _model = create_model(_factory.class_name, **_factory.model_fields) 35 | >> _instance = dynamic_model.model_validate(json_with_data) 36 | >> validated_data = model_instance.model_dump() 37 | """ 38 | self.class_name = json_schema.get('title') 39 | self.class_type = json_schema.get('type') 40 | self.required = json_schema.get('required', False) 41 | self.raw_fields = json_schema.get('properties') 42 | self.ref_template = ref_template 43 | self.definitions = json_schema.get(ref_template) 44 | self.fields = {} 45 | self.model_fields = {} 46 | self._base_model = base_model 47 | 48 | def make(self) -> Model: 49 | """Factory method, dynamically creates a pydantic model from JSON Schema""" 50 | for field in self.raw_fields: 51 | if '$ref' in self.raw_fields[field]: 52 | model_name = self.raw_fields[field].get('$ref') 53 | self._make_nested(model_name, field) 54 | else: 55 | factory = self.TYPES.get(self.raw_fields[field].get('type')) 56 | if factory == list: 57 | items = self.raw_fields[field].get('items') 58 | if self.ref_template in items: 59 | self._make_nested(items.get(self.ref_template), field) 60 | self._make_field(factory, field, self.raw_fields.get('title')) 61 | return create_model(self.class_name, __base__=self._base_model, **self.model_fields) 62 | 63 | def _make_nested(self, model_name: str, field) -> None: 64 | """Create a nested model""" 65 | level = DyntamicFactory({self.ref_template: self.definitions} | self.definitions.get(model_name), 66 | ref_template=self.ref_template) 67 | level.make() 68 | model = create_model(model_name, **level.model_fields) 69 | self._make_field(model, field, field) 70 | 71 | def _make_field(self, factory, field, alias) -> None: 72 | """Create an annotated field""" 73 | if field not in self.required: 74 | factory_annotation = Annotated[Union[factory | None], factory] 75 | else: 76 | factory_annotation = factory 77 | self.model_fields[field] = ( 78 | Annotated[factory_annotation, Field(default_factory=factory, alias=alias)], 79 | ...) 80 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | from dyntamic.factory import DyntamicFactory 2 | 3 | 4 | def test_schema_generation(): 5 | """Test model generation and validation by this model""" 6 | schema = { 7 | "$defs": { 8 | "Nested": { 9 | "properties": { 10 | "id": { 11 | "title": "Id", 12 | "type": "string" 13 | }, 14 | "sum": { 15 | "title": "Sum", 16 | "type": "number" 17 | } 18 | }, 19 | "required": [ 20 | "id", 21 | "sum" 22 | ], 23 | "title": "Nested", 24 | "type": "object" 25 | }, 26 | "Nested2": { 27 | "properties": { 28 | "id2": { 29 | "title": "Id2", 30 | "type": "string" 31 | }, 32 | "sum2": { 33 | "title": "Sum2", 34 | "type": "number" 35 | }, 36 | "nested": { 37 | "$ref": "Nested" 38 | } 39 | }, 40 | "required": [ 41 | "id2", 42 | "sum2", 43 | "nested" 44 | ], 45 | "title": "Nested2", 46 | "type": "object" 47 | } 48 | }, 49 | "properties": { 50 | "name": { 51 | "title": "Name", 52 | "type": "string" 53 | }, 54 | "address": { 55 | "title": "Address", 56 | "type": "integer" 57 | }, 58 | "is_b": { 59 | "title": "Is B", 60 | "type": "boolean" 61 | }, 62 | "some_value_1": { 63 | "items": { 64 | "$ref": "Nested" 65 | }, 66 | "title": "Some L", 67 | "type": "array" 68 | }, 69 | "some_value_2": { 70 | "items": { 71 | "$ref": "Nested2" 72 | }, 73 | "title": "Some L2", 74 | "type": "array" 75 | }, 76 | "some_value_3": { 77 | "$ref": "Nested" 78 | }, 79 | "some_value_4": { 80 | "items": { 81 | "type": "string" 82 | }, 83 | "title": "Some L4", 84 | "type": "array" 85 | } 86 | }, 87 | "required": [ 88 | "name", 89 | "address", 90 | "is_b", 91 | "some_value_1", 92 | "some_value_2", 93 | "some_value_3" 94 | ], 95 | "title": "TestSchema", 96 | "type": "object" 97 | } 98 | f = DyntamicFactory(schema, ref_template="$defs") 99 | model = f.make() 100 | assert model 101 | sample_data = { 102 | "name": "Some name", 103 | "address": 12, 104 | "is_b": True, 105 | "some_value_1": [ 106 | {"id": "1", "sum": 123.0} 107 | ], 108 | "some_value_2": [ 109 | {"id2": "1", "sum2": 123.0, "nested": {"id": "1", "sum": 123.0}} 110 | ], 111 | "some_value_3": {"id": "1", "sum": 123.0}, 112 | "some_value_4": ["asd", "adsads"] 113 | } 114 | validated_model = model.model_validate(sample_data) 115 | dumped_data = validated_model.model_dump() 116 | assert dumped_data == sample_data 117 | --------------------------------------------------------------------------------