Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Client and server-side validation
Lecture: Viewmodel data exchange
0:00 Few models provide two basic services.
0:02 They provide data exchange and normalization.
0:05 And they also provide validation.
0:07 So we saw this way of taking a request
0:10 and converting it into a dictionary
0:12 through the view model was super valuable.
0:14 So let's see how that goes.
0:16 We're going to have this view model based class
0:17 and all of the models will derive from it
0:19 it's going to have this constructor.
0:21 And here we're going to initialize the standard shared data
0:23 maybe everything wants to get a hold request
0:26 we're going to have an error set just in case
0:28 or at least an error present, not central value
0:31 but it'll be present in the dictionary
0:33 as well as what the user ideas and our actual code
0:36 we actually went to the cookie often got that out.
0:38 So it was passed back through a cookie
0:40 was automatically set here.
0:42 Now how do we get these fields
0:43 and all the one set by the derived classes
0:46 over as a dictionary, super simple
0:48 we just call self.to_dict.
0:50 So the concrete view models like the registration one
0:54 and package management one
0:56 or whatever ones we create
0:57 are just going to set fields than the standard dict
1:00 is going to have all those fields
1:01 and it will just pass them along.
1:03 And that's how we do data exchange.
1:05 Now in the concrete view model
1:07 so when they derive from the base that are actually modeled
1:09 for a particular view
1:11 we're going to do something a little bit different.
1:13 So over here, we have our registration remodeled
1:15 derived from ViewModelBase
1:17 itself going to have this constructor
1:20 and it's going to call the super's initialization
1:23 or constructor that's going to set all the base stuff
1:25 and then it's going to go to the request
1:28 maybe go to the form, get the name
1:29 do the normalization
1:30 and store all of these things right here.
1:33 That way when we return the __dict__
1:36 out of the ViewModelBase
1:37 it's going to have first_name, last_name, email
1:39 password, full_name
1:40 and all the stuff that the base class set as well.
1:42 It works like a charm.