form_validation.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from pydantic import BaseModel, EmailStr, field_validator
  2. import nh3
  3. import pycountry
  4. class FormCheckoutSession(BaseModel):
  5. order_id: str
  6. weight: int
  7. email: EmailStr
  8. first_name: str
  9. last_name: str
  10. address: str
  11. address_no: str
  12. address_extra: str
  13. postal_code: str
  14. city: str
  15. country: str
  16. phone_number: str
  17. note: str
  18. @field_validator('order_id', 'first_name', 'last_name',
  19. 'address', 'address_no', 'address_extra',
  20. 'postal_code', 'city', 'country', 'note')
  21. @classmethod
  22. def check_xss(cls, v: str) -> str:
  23. return nh3.clean(v)
  24. @field_validator('weight')
  25. @classmethod
  26. def check_weight(cls, v: str) -> str:
  27. if v <= 0:
  28. raise ValueError('Weight should be a positive number.')
  29. return v
  30. @field_validator('country')
  31. @classmethod
  32. def check_country(cls, v: str) -> str:
  33. countries = [country.name for country in pycountry.countries]
  34. if v not in countries:
  35. raise ValueError('Country is not part of valid list of countries.')
  36. return v
  37. def form_validation_checkout_session(form_data):
  38. """
  39. Prepare dictionary with form data and validate it against a
  40. specific ruleset that checks for:
  41. - weight to be positive int
  42. - email to be proper email format
  43. - country to be part of allowed country
  44. - any str for "XSS"
  45. """
  46. data = {
  47. "order_id": form_data["order_id"],
  48. "weight": form_data["weight"],
  49. "email": form_data["email"],
  50. "first_name": form_data["first_name"],
  51. "last_name": form_data["last_name"],
  52. "address": form_data["address"],
  53. "address_no": form_data["address_no"],
  54. "address_extra": form_data["address_extra"],
  55. "postal_code": form_data["postal_code"],
  56. "city": form_data["city"],
  57. "country": form_data["country"],
  58. "phone_number": form_data["phone_number"],
  59. "note": form_data["note"],
  60. }
  61. form = FormCheckoutSession(**data)
  62. return form