-
I am using zod to validate a schema and I have field I want set to an object. I can't really see a way to do
In my Client Code / Form: def make_model_from_ui(self) -> ParticipantRegistration:
my_logger.debug("ENTERING: make_model_from_ui")
try:
_new_reg = ctrl.participant_registration_factory(
{"first_name": self.text_box_first_name.text,
"last_name": self.text_box_last_name.text,
"email": self.text_box_email.text,
"phone": self.text_box_phone.text,
"timezone_name": self.drop_down_timezone.selected_value,
"age_range": self.drop_down_age_range.selected_value,
"preferred_contact_methods": self.multi_select_drop_down_contact_prefs.selected,
"motivation_goal_reason_notes": None,
"registration_notes": self.text_area_reg_notes.text,
"internal_notes": self.text_area_internal_notes.text,
"workshop": self.drop_down_workshop.selected_value,
"program": self.drop_down_program.selected_value,
"program_other_text": self.text_box_program_other.text,
"partner_program_sequence_name": None,
"registered_by": "BuildEd", # TODO: Update with user once SSO is configured,
"modified_by": "WebApp", # TODO: Update with user once SSO is configured
}
)
return _new_reg
except z.ParseError as err:
alert(f"Registration data not complete or the data entered is malformed.\n\n{err}") The "factory" code in a controller module. def participant_registration_factory(in_data:dict) -> ParticipantRegistration:
"""
Validate an input dictionary and if passes validation, return a valid model object
"""
try:
_val_dict = schemas.new_registration_schema.parse(in_data)
_reg = ParticipantRegistration(**_val_dict)
return _reg
except z.ParseError as err:
raise err My Zod Schema from anvil_extras import zod as z
new_registration_schema = z.typed_dict({
# "id": z.string().uuid(),
"first_name": z.string().strip(),
"last_name": z.string().strip(),
"email": z.string().email(),
"phone": z.string(),
"timezone_name": z.string(),
"age_range": z.string(),
"preferred_contact_methods": z.string().list().optional(),
"motivation_goal_reason_notes": z.string().optional(),
"registration_notes": z.string().optional(),
"internal_notes": z.string().optional().not_required(),
"workshop": z.any(),
"program": z.string(),
"program_other_text": z.string().optional(),
"partner_program_sequence_name": z.string().optional(),
"registered_by": z.string(),
"modified_by": z.string()
}
) I am using A more formal approach would be (or I didn't notice any candidates when I read the I don't think this is necessary, but for completeness, the server code creates a new registration. @anvil.server.callable
def create_new_participant_registrataion(new_reg: ParticipantRegistration) -> ParticipantRegistration:
my_logger.debug(f"ENTERING: create_new_participant_registrataion: {new_reg}")
my_logger.debug(f"LINKED Workshop: {new_reg.workshop.id}")
workshop_row = find_row_by_model(new_reg.workshop)
new_row = app_tables.participant_registrations.add_row(first_name=new_reg.first_name,
last_name=new_reg.last_name,
email=new_reg.email,
phone=new_reg.phone,
timezone_name=new_reg.timezone_name,
age_range=new_reg.age_range,
preferred_contact_methods=new_reg.preferred_contact_methods,
motivation_goal_reason_notes=new_reg.motivation_goal_reason_notes,
registration_notes=new_reg.registration_notes,
internal_notes=new_reg.internal_notes,
program=new_reg.program,
program_other_text=new_reg.program_other_text,
partner_program_sequence_name=new_reg.partner_program_sequence_name,
reschedule_count=0,
registered_by=new_reg.registered_by,
modified_by=new_reg.modified_by,
workshop=workshop_row,
id=new_reg.id,
modified=datetime.now(timezone.utc))
new_reg = ParticipantRegistration(**dict(new_row))
if new_reg.workshop:
new_reg.workshop = Workshop(**dict(new_row['workshop']))
return new_reg and finally the model definitions @anvil.server.portable_class("_Workshop")
class Workshop():
def __init__(self, **kwargs):
self.id: str = kwargs.get('id', str(uuid.uuid4()))
self.workshop_name: str = kwargs.get('workshop_name')
self.workshop_type: str = kwargs.get('workshop_type')
self.day_one_start_time: datetime = kwargs.get('day_one_start_time') # Datetime
self.day_one_duration: int = kwargs.get('day_one_duration', 5)
self.day_two_start_time: datetime = kwargs.get('day_two_start_time', None) # Datetime
self.day_two_duration = kwargs.get('day_two_duration', 5)
self.is_spanish_workshop: bool = kwargs.get('is_spanish_workshop', False)
self.is_private_workshop: bool = kwargs.get('is_private_workshop', False)
self.is_locked: bool = kwargs.get('is_locked', False)
self.notes: str = kwargs.get('notes')
self.facilitator: Facilitator = kwargs.get('facilitator', None)
self.modified_date: datetime = kwargs.get('modified_date')
@anvil.server.portable_class("_ParticipantRegistration")
class ParticipantRegistration():
def __init__(self, **kwargs):
self.id: str = kwargs.get('id', str(uuid.uuid4()))
self.first_name: str = kwargs.get('first_name')
self.last_name: str = kwargs.get('last_name')
self.email: str = kwargs.get('email')
self.phone: str = kwargs.get('phone')
self.timezone_name: str = kwargs.get('timezone_name')
self.age_range:str = kwargs.get('timezone_name')
self.preferred_contact_methods = kwargs.get('preferred_contact_methods', None)
self.motivation_goal_reason_notes: str = kwargs.get('motivation_goal_reason_notes')
self.registration_notes: Optional[str] = kwargs.get('registration_notes')
self.internal_notes: Optional[str] = kwargs.get('internal_notes')
self.workshop: Workshop = kwargs.get('workshop')
self.program: Program = kwargs.get('program')
self.program_other_text: str = kwargs.get('program_other_text', None)
self.partner_program_sequence_name: str = kwargs.get('partner_program_sequence', None)
self.reschedule_history = kwargs.get('reschedule_history', None)
self.reschedule_count: int = kwargs.get('reschedule_count', 0)
self.attended: bool = kwargs.get('attended', False)
self.completed: bool = kwargs.get('completed', False)
self.credentialed: bool = kwargs.get('credentialed', False)
self.registered_by: str = kwargs.get('registered_by')
self.modified_by: str = kwargs.get('modified_by')
self.modified_date: datetime = kwargs.get('modified_date') |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Is If you're into PRs maybe you could PR this into the docs where it was missing? Note you can also use refine: z.any().refine(lambda x: x is not None) |
Beta Was this translation helpful? Give feedback.
-
Sheesh ... I really question my ability to search documentation, as |
Beta Was this translation helpful? Give feedback.
Is
z.isinstance
what you need?If you're into PRs maybe you could PR this into the docs where it was missing?
Note you can also use refine: