-
-
Save Isaac3N/9926edfbd5424b8b9139f473e448ed46 to your computer and use it in GitHub Desktop.
Example of how to use pydantic
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
from pydantic import BaseModel | |
from typing import Optional #this is to enable more complex field types | |
from random import randrange #to import a random integer | |
class Product(BaseModel): | |
title: str | |
description: str | |
price: int | |
ratings: Optional[int] = None | |
published: Optional[bool]= True | |
id: Optional[int]= None | |
#The optional keyword is used to indicated that the field is not required to be filled. It is then given a default value | |
data = { | |
"title": "Iphone 13 pro max", | |
"description": "This is the latest Iphone from apple", | |
"price": 1000, | |
"ratings": 4.56, | |
"id": randrange(0, 100000000) #creates a random integer between 0 and 100000000 | |
} | |
product = Product(**data) #to read the python dictionary | |
print(product) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment