Step-Bless Study in good verification and create user data, product, and data ordering onydantic in Python

In many modern Python exams, especially those that manage incoming data (eg JSON to load from API), to ensure that data works, perfect, and properly typing important. The Widiles Is the strong library that allows your data models using normal Python-Type plans and confirms any incoming data against these types. In this example, we will show how to model the usual way to use: the user sets for product order. We will use the Pydantic to explain user models, product, order models, to ensure that data such as emails, prices, prices, and user details that are specific.
Step 1: Add reliance
pip install pydantic
pip install pydantic[email]
Use to include PIP Pydantic to include Core Library, enabling data authentication with Python types of Python. Also, run PIP Install Pydantic[email] With the features of a built-in email.
Step 2: Describe the Pydantic Models (User, Product, and Organization)
from typing import List, Optional
from pydantic import BaseModel, Field, EmailStr, conint, ValidationError
# Define the models
class User(BaseModel):
name: str = Field(..., min_length=1, max_length=50, description="User's full name")
email: EmailStr = Field(..., description="User's email address, validated by Pydantic")
age: Optional[conint(ge=0, le=120)] = Field(None, description="Optional age with a realistic range")
phone_number: Optional[str] = Field(None, pattern=r'^+?[1-9]d{1,14}$', description="Optional phone number, E.164 format")
class Product(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0, description="Price must be greater than zero")
quantity: conint(gt=0) = Field(..., description="Quantity must be greater than zero")
class Order(BaseModel):
order_id: int = Field(..., gt=0, description="Order ID must be a positive integer")
user: User
products: List[Product] = Field(..., description="A list of products in the order")
# Computed property
@property
def total_cost(self) -> float:
return sum(product.price * product.quantity for product in self.products)
By using the above code, these three pydantic models, user, product, product and order, provide systematic, certified application management system. The user commits the issues of the name, email, ages, and the optional telephone number corresponding to the pattern. The product guarantees a valid name length, good price, and non-zero value. Finally, the order ties to the user and products together while pointing to the cost of the order.
Step 3: Use verification to a large work ()
def main():
# Example of a valid user dictionary
user_data = {
"name": "Jane Doe",
"email": "[email protected]",
"age": 30,
"phone_number": "+1234567890"
}
# Example of product data
products_data = [
{"name": "Keyboard", "price": 49.99, "quantity": 1},
{"name": "Mouse", "price": 19.99, "quantity": 2}
]
# Combine user and products in an order
order_data = {
"order_id": 101,
"user": user_data,
"products": products_data
}
try:
# Instantiate models to trigger validation
valid_user = User(**user_data)
print("User Model:", valid_user)
valid_products = [Product(**pd) for pd in products_data]
print("Product Models:", valid_products)
valid_order = Order(**order_data)
print("Order Model:", valid_order)
print(f"Total cost of the order: {valid_order.total_cost}")
except ValidationError as e:
print("Validation Error:", e)
Now, this primary function () imitating imitations for accessing user data and multiple products, and creates and confirms the corresponding user, product, and order conditions. It shows how the Pydatic suggests the VarieError if any data fails to be verified and prints guaranteed models and total total value.
Step 4: Make a program
# Run the main() function
main()
We are very expensive () to make a demonstration, guaranteeing our example of the example, product, and order data. After using work, printing the guaranteed models and any errors when the data fails to be verified.
Output
User Model: name="Jane Doe" email="[email protected]" age=30 phone_number="+1234567890" Product Models: [Product(name="Keyboard", price=49.99, quantity=1), Product(name="Mouse", price=19.99, quantity=2)] Order Model: order_id=101 user=User(name="Jane Doe", email="[email protected]", age=30, phone_number="+1234567890") products=[Product(name="Keyboard", price=49.99, quantity=1), Product(name="Mouse", price=19.99, quantity=2)] Total cost of the order: 89.97
Code release will be more.
In this example, we demonstrated how the pydalatic can describe and ensure the user's data models, product, and order within the actual work of work. Pydantic confirms that any data provided these types are correct by specifying the types of field, issues, and custom verification. This helps you to hold errors in advance, simplify your logic code, and strengthen the credibility of the powerful data apps.
Here is the Colab Notebook of the above project. Also, don't forget to follow Sane and join ours Telegraph station including LinkedIn Grtopic. Don't forget to join ours 75k + ml subreddit.
🚨 Recommended for an open source of AI' (Updated)
Asphazzaq is a Markteach Media Inc. According to a View Business and Developer, Asifi is committed to integrating a good social intelligence. His latest attempt is launched by the launch of the chemistrylife plan for an intelligence, MarktechPost, a devastating intimate practice of a machine learning and deep learning issues that are clearly and easily understood. The platform is adhering to more than two million moon visits, indicating its popularity between the audience.
✅ [Recommended] Join Our Telegraph Channel