Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Client and server-side validation
Lecture: Concept: Viewmodel
0:00 You've seen view models in action
0:01 let's review them as a general concept.
0:04 So here's a mock up of a web browser
0:08 some sort of architectural view of our server
0:11 and the user of the web browser submitting a form.
0:14 Here they're doing their HTTP POST
0:15 for the register action form page.
0:19 And they're submitting some form data
0:21 which we didn't elaborate too much on here
0:23 but you see some sort of form data is being submitted.
0:26 Now, the way that Flask encourages you to handle this
0:29 in general, and a lot of the web framers do
0:33 is to just have some super complicated view method.
0:38 Why? Well, there's no other pattern to tell you
0:41 it doesn't have to be that way
0:43 cause you have to do all the data acquisition
0:45 the data normalization like stripping
0:47 and lower-casing the email, stuff like that.
0:50 You've got to do the validation
0:52 you've got to do lots of testing
0:53 like does this user already exist?
0:55 Typically, here's the function where you do that.
0:58 Go to town, sorry it's 200 lines.
1:00 All right, things like that.
1:01 But it doesn't have to be that way.
1:02 We saw the view model pattern takes the data exchange
1:06 the data normalization, and the data validation
1:08 and it pushes it somewhere else
1:10 that can be tested separately, maintained separately.
1:13 And our view method only has to process the essence.
1:17 It gets the data, maybe it creates the user
1:19 and it doesn't redirect, or something to that effect.
1:22 Sends them a welcome email, things like this.
1:23 So we can exchange this yellow box
1:25 for a much smaller, more maintainable version
1:28 and instead of writing all that validation
1:30 and exchange data, we create a view model
1:32 and we just work with that view model over here.
1:35 Now this is the general idea
1:38 of this view model design pattern.