Last active
March 15, 2021 10:58
-
-
Save navhits/2c5c9f1ca294d375dce08dc3587d52c7 to your computer and use it in GitHub Desktop.
A demonstration of getting values for a Pydantic model from std input, validating it back with same model and exporting it, in Python using Pydantic library. The code should be run as-is. You can make changes to the pydantic model if you'd like to see how it works.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This snippet reads a Pydantic model and gets data via std input and validates them back with the same model. This validated data can be exported for further processing in your own code. | |
from pydantic import BaseModel, AnyUrl | |
from typing import Optional | |
# Create a Pydantic Model. All Pydantic models needs be validated as dictionary mappings. A model can also contain a sub model. Such feature can be used to validate a Dictionary object within a dictionary. Pydantic also provides ways to validate data without creating models. For more info refer the docs, https://pydantic-docs.helpmanual.io/ | |
class MyModel(BaseModel): | |
name: str = None # Demonstrating the bahaviour of providing default value as None | |
title: Optional[str] # Demonstrating the behavior when using Optional without setting a default value (will auto default to None) | |
url: AnyUrl # AnyUrl validates URL with any schema, domain, path, etc without strictly checking them. Pydantic provides more Url validation options. Check the docs, https://pydantic-docs.helpmanual.io/usage/types/#urls | |
number: int | |
decimal_number: float | |
schema = MyModel.schema() | |
''' | |
{'properties': {'decimal_number': {'title': 'Decimal Number', | |
'type': 'number'}, | |
'name': {'title': 'Name', 'type': 'string'}, | |
'number': {'title': 'Number', 'type': 'integer'}, | |
'title': {'title': 'Title', 'type': 'string'}, | |
'url': {'format': 'uri', | |
'maxLength': 65536, | |
'minLength': 1, | |
'title': 'Url', | |
'type': 'string'}}, | |
'required': ['url', 'number', 'decimal_number'], | |
'title': 'MyModel', | |
'type': 'object'} | |
''' | |
mandatory_fields = schema['required'] | |
fields = [key for key in schema['properties'].keys()] | |
def get_mandatory(field: str) -> str: | |
temp = input(f'Input value for {field} (mandatory): ') | |
while temp is '': | |
temp = input(f'{field} is mandatory. Enter a value: ') | |
return temp | |
def get_non_mandatory(field: str)-> (str, None): | |
temp = input(f'Input value for {field}: ') | |
return temp if temp is not '' else None | |
dictionary = {field:(get_mandatory(field) if field in mandatory_fields else get_non_mandatory(field)) for field in fields} | |
# Input value for name: | |
# Input value for title: Demo | |
# Input value for url (mandatory): | |
# url is mandatory. Enter a value: http://google.com | |
# Input value for number (mandatory): | |
# number is mandatory. Enter a value: 1 | |
# Input value for decimal_number (mandatory): 12.1 | |
print(MyModel(**dictionary)) | |
# name=None title='Demo' url=AnyUrl('http://google.com', scheme='http', host='google.com', tld='com', host_type='domain') number=1 decimal_number=12.1 | |
print(MyModel(**dictionary).dict()) | |
# {'name': None, 'title': 'Demo', 'url': AnyUrl('http://google.com', scheme='http', host='google.com', tld='com', host_type='domain'), 'number': 1, 'decimal_number': 12.1} | |
print(MyModel(**dictionary).json()) | |
# {"name": null, "title": "Demo", "url": "http://google.com", "number": 1, "decimal_number": 12.1} | |
# Further each object can also be exported like this. Once a Pydantic model is validated it also parses the data and it acts like a normal class. So we can access the class objects as usual. All the class objects will be JSON serialized by default. | |
print(m.name) | |
print(m.title) | |
print(m.url) | |
print(m.number) | |
print(m.decimal_number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment