Skip to content

Commit

Permalink
Replace field validators with pydantic tooling
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed Nov 15, 2023
1 parent 16bba40 commit f62ee3e
Showing 1 changed file with 2 additions and 16 deletions.
18 changes: 2 additions & 16 deletions app/schemas.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
from datetime import date
from datetime import datetime

Expand All @@ -22,33 +21,20 @@ class UserBase(BaseModel):
class PriceCreate(BaseModel):
model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True)

product_code: str = Field(min_length=1)
product_code: str = Field(min_length=1, pattern="^[0-9]+$")
price: float
currency: str | Currency
location_osm_id: int
location_osm_id: int = Field(gt=0)
location_osm_type: PriceLocationOSMType
date: date

@field_validator("product_code")
def product_code_must_be_only_numbers(cls, v):
regex = r"^[0-9]+$"
if not re.match(regex, v):
raise ValueError("must only contain numbers")
return v

@field_validator("currency")
def currency_is_valid(cls, v):
try:
return Currency(v).code
except ValueError:
raise ValueError("not a valid currency code")

@field_validator("location_osm_id")
def location_osm_id_must_be_positive(cls, v):
if v <= 0:
raise ValueError("must be positive")
return v

@field_serializer("currency")
def serialize_currency(self, currency: Currency, _info):
if type(currency) is Currency:
Expand Down

0 comments on commit f62ee3e

Please sign in to comment.