Last active
June 19, 2021 07:47
-
-
Save Proteusiq/ef4c1e13bcbbb759e300522d84ea59be to your computer and use it in GitHub Desktop.
This file contains hidden or 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 datetime import datetime | |
from uuid import UUID, uuid4 | |
from typing import Literal, Optional, Union | |
from pydantic import BaseModel, Field, ValidationError, validator, constr, confloat | |
class HouseDataValidation(BaseModel): | |
id: Union[int, UUID] = Field(default_factory=uuid4) | |
kind: Literal["villa", "apartment", "townhouse"] | |
sales_date: datetime | |
downpayment: Optional[confloat(ge=0)] = 0.0 | |
price: confloat(gt=1e3, lt=1e10) | |
comment: Optional[constr(max_length=300)] = None | |
@validator("sales_date") | |
def sales_date_validation(cls, v): | |
# sales date cannot be none or more than 31 days old | |
if v is None: | |
raise ValueError("sales date cannot be None") | |
today = datetime.now() | |
sales_days_old = (today - v).days | |
if sales_days_old > 31: | |
raise ValueError( | |
f"sales is {sales_days_old} days old. " | |
"sales date cannot be more than 31 days old" | |
) | |
return v | |
@validator("price") | |
def sales_validation(cls, v, values): | |
# price cannot lower than downpayment | |
if values.get("downpayment") and v < values["downpayment"]: | |
raise ValueError( | |
f"sales price {v} cannot be lower " | |
f"than downpayment: {values['downpayment']}." | |
) | |
return v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment