Skip to content

Instantly share code, notes, and snippets.

@janaki-sasidhar
Created June 28, 2021 08:31
Show Gist options
  • Save janaki-sasidhar/923c8a8f4214535cb3e8e3f92f1a1f1f to your computer and use it in GitHub Desktop.
Save janaki-sasidhar/923c8a8f4214535cb3e8e3f92f1a1f1f to your computer and use it in GitHub Desktop.
import json
import pydantic
from typing import Optional , List
books_list = '''[
{
"isbn_10": "1593279509",
"isbn_13": "1593279509",
"title": "Eloquent JavaScript, Third Edition",
"subtitle": "A Modern Introduction to Programming",
"author": "Marijn Haverbeke",
"publisher": "No Starch Press",
"price": 47.2
},
{
"isbn_10": "1491943533",
"isbn_13": "1491943533",
"title": "Practical Modern JavaScript",
"subtitle": "Dive into ES6 and the Future of JavaScript",
"author": "Nicolás Bevacqua",
"publisher": "O'Reilly Media",
"price": 33.4
},
{
"isbn_10": "1491943533",
"isbn_13": "1491943533",
"title": "Understanding ECMAScript 6",
"subtitle": "The Definitive Guide for JavaScript Developers",
"author": "Nicholas C. Zakas",
"publisher": "No Starch Press",
"price": 35.2
},
{
"isbn_10": "1449365035",
"isbn_13": "1449365035",
"title": "Speaking JavaScript",
"subtitle": "An In-Depth Guide for Programmers",
"author": "Axel Rauschmayer",
"publisher": "O'Reilly Media",
"price": 46.0
},
{
"isbn_10": "1449331818",
"isbn_13": "1449331818",
"title": "Learning JavaScript Design Patterns",
"subtitle": "A JavaScript and jQuery Developer's Guide",
"author": "Addy Osmani",
"publisher": "O'Reilly Media",
"price": 25.4
},
{
"isbn_10": "8602477429",
"isbn_13": "8602477429",
"title": "You Don't Know JS Yet",
"subtitle": "Get Started",
"author": "Kyle Simpson",
"publisher": "Independently published",
"price": 14.3
}]'''
class ISBN10FormatError(Exception):
def __init__(self , value:str , message:str) -> None:
self.value=value
self.message=message
super().__init__(message)
class ISBNNotFoundError(Exception):
def __init__(self , values:str , message:str) -> None:
self.values=values
self.message=message
super().__init__(message)
class Book(pydantic.BaseModel):
title : str
author : str
publisher : str
price : float
isbn_10: Optional[str]
isbn_13 : Optional[str]
subtitle : Optional[str]
# ADDING VALIDATION FOR PYDANTIC
@pydantic.validator("isbn_10")
@classmethod
def isbn_10_valid(cls,value):
chars = [c for c in value if c in '0123456789xX']
if len(chars) !=10:
raise ISBN10FormatError(value=value,message="ISBN10 Should be 10 digits")
return value
@pydantic.root_validator(pre=True)
@classmethod
def isbn_10_or_isbn_13_present(cls,values):
if 'isbn_10' not in values and 'isbn_13' not in values:
raise ISBNNotFoundError(values=values,message='ATLEAST ONE ISBN MUST BE PRESENT')
return values
class Config:
'''MAKES BOOK IMMUTABLE'''
allow_mutation = False
anystr_lower = True # makes any string value lower
def main() -> None:
data = json.loads(books_list)
books:List[Book] = [Book(**item) for item in data]
print(books[0]) # PYDANTIC MODEL , USE dir(books) to get the properties and methods
'''
books[0] is a pydantic model and has methods like , books[0].to_dict() , books[0].to_json() and to_dict() has some arguments that can be passed like include (includes only that) and exclued(exclues that particular item in json dict)etc.
'''
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment