from pydantic import BaseModel, EmailStr, field_validator import nh3 import pycountry class FormCheckoutSession(BaseModel): order_id: str weight: int email: EmailStr first_name: str last_name: str address: str address_no: str address_extra: str postal_code: str city: str country: str phone_number: str note: str @field_validator('order_id', 'first_name', 'last_name', 'address', 'address_no', 'address_extra', 'postal_code', 'city', 'country', 'note') @classmethod def check_xss(cls, v: str) -> str: return nh3.clean(v) @field_validator('weight') @classmethod def check_weight(cls, v: str) -> str: if v <= 0: raise ValueError('Weight should be a positive number.') return v @field_validator('country') @classmethod def check_country(cls, v: str) -> str: countries = [country.name for country in pycountry.countries] if v not in countries: raise ValueError('Country is not part of valid list of countries.') return v def form_validation_checkout_session(form_data): """ Prepare dictionary with form data and validate it against a specific ruleset that checks for: - weight to be positive int - email to be proper email format - country to be part of allowed country - any str for "XSS" """ data = { "order_id": form_data["order_id"], "weight": form_data["weight"], "email": form_data["email"], "first_name": form_data["first_name"], "last_name": form_data["last_name"], "address": form_data["address"], "address_no": form_data["address_no"], "address_extra": form_data["address_extra"], "postal_code": form_data["postal_code"], "city": form_data["city"], "country": form_data["country"], "phone_number": form_data["phone_number"], "note": form_data["note"], } form = FormCheckoutSession(**data) return form