Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions HWs/DmitriyK/HM2/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import pydantic
from pydantic import BaseModel, EmailStr, Field, model_validator

class Address(BaseModel):
city: str = Field(..., min_length=2)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

С версии 2.0 в pydantic не нужно указывать ... для обозначения обязательного поля, о чем я говорил на занятии.

Suggested change
city: str = Field(..., min_length=2)
city: str = Field(min_length=2)

street: str = Field(..., min_length=3)
house_number: int = Field(..., gt=0)

class User(BaseModel):
name: str = Field(..., min_length=2, pattern=r"^[a-zA-Z\s]+$")
age: int = Field(..., ge=0, le=120)
email: EmailStr
is_employed: bool
address: Address

@model_validator(mode='after')
def validate_employment_age(self) -> 'User':
if self.is_employed:
if not (18 <= self.age <= 65):
Comment on lines +18 to +19

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше перечислить эти условия через and

Suggested change
if self.is_employed:
if not (18 <= self.age <= 65):
if self.is_employed and not (18 <= self.age <= 65):

raise ValueError(
f"Employed users must be between 18 and 65 years old. "
f"Current age provided: {self.age}"
)
return self


def process_user_registration(json_str: str) -> str:
"""
Deserializes JSON, validates data using Pydantic,
and serializes it back to JSON.
"""
try:
user = User.model_validate_json(json_str)
return user.model_dump_json(indent=4)
except pydantic.ValidationError as e:
return f"Validation error: {e.json()}"

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень хорошо, когда функция возвращает различные структуры данных.

Suggested change
return f"Validation error: {e.json()}"
return e.json()


if __name__ == "__main__":
success_json = """{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"is_employed": true,
"address": {
"city": "Berlin",
"street": "Friedrichstrasse",
"house_number": 101
}
}"""

failed_age_json = """{
"name": "Old Working Man",
"age": 70,
"email": "oldman@example.com",
"is_employed": true,
"address": {"city": "Hamburg", "street": "Reeperbahn", "house_number": 5}
}"""

print("--- SUCCESS CASE ---")
print(process_user_registration(success_json))

print("\n--- FAILED CASE (Age 70 + Employed) ---")
print(process_user_registration(failed_age_json))