Pydantic: possibility of create_model from a schema JSON

Created on 29 Apr 2020  路  3Comments  路  Source: samuelcolvin/pydantic

possibility of create_model from a schema JSON

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.5.1
            pydantic compiled: True
                 install path: /Users/xiaojuwang/.virtualenvs/pydantic/lib/python3.7/site-packages/pydantic
               python version: 3.7.7 (default, Mar 10 2020, 15:43:27)  [Clang 10.0.0 (clang-1000.11.45.5)]
                     platform: Darwin-17.7.0-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

Thanks Samuel for making such a great lib, you rock!

After reading the docs, I know there are create_model() for dynamic model creation and .schema_json() to export model to JSON.

I wonder if pydantic can convert some JSON with format of .schema_json() back to a model. In some scenarios, it's easier than manual create_model().

Say, use can create their own preferred setting for temperature and humidity.

class PreferredSetting(BaseModel):
    temperature: conint(gt=18, lt=25)
    humidity: conint(gt=40, lt=50)

User can customize via YAML:

title: MyPreferredSetting
type: object
properties:
  temperature:
    title: Temperature
    type: integer
    exclusiveMinimum: 16
    exclusiveMaximum: 20
  humidity:
    title: Humidity
    type: integer
    exclusiveMinimum: 30
    exclusiveMaximum: 45
required:
- temperature
- humidity

YAML is uploaded and saved. Backend program can parse it to JSON and create pydantic model then validate.

question

Most helpful comment

Hi @vvoody
Have you checked https://github.com/samuelcolvin/pydantic/issues/643 ?
It leads to https://koxudaxi.github.io/datamodel-code-generator/jsonschema/ !
Hope it helps :)

All 3 comments

Hi @vvoody
Have you checked https://github.com/samuelcolvin/pydantic/issues/643 ?
It leads to https://koxudaxi.github.io/datamodel-code-generator/jsonschema/ !
Hope it helps :)

See also #1405

Thanks @PrettyWood and @samuelcolvin !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dconathan picture dconathan  路  3Comments

gangefors picture gangefors  路  3Comments

dmontagu picture dmontagu  路  3Comments

timonbimon picture timonbimon  路  3Comments

cdeil picture cdeil  路  3Comments