Chapter: Surveying the non-js-enabled Flask app
Lecture: Concept: View models
0:00 When we're working on the web in Flask, very often what we need to do is
0:04 take some data and provide it to the HTML template and Flask will combine that with
0:09 Jinja, do a bunch of work to actually turn it into HTML and return it to the
0:14 client directly for us. This data exchange can be tricky.
0:19 So we're using this idea of View models. Now, View models are classes that are dedicated
0:24 basically to that template file. It knows what that template file needs and if it accepts
0:30 data it knows what data, say through a form or something, that that template might send
0:34 back. So it does both validation, as well as that transformation.
0:38 A little bit like Pydantic, but it turns out Pydantic doesn't make a lot of
0:41 sense in this scenario. So the way it works in our applications
0:45 is we have this thing called the ViewModelBase and its primary job is really to
0:50 return itself as a dictionary, and it just leverages its fields, it says my fields are whatever
0:56 as a dictionary. Then we can derive from that.
0:59 In our case we saw the IndexViewModel was the homepage, it has categories and
1:04 it has rows. So it does all the querying and data transformation that might be
1:09 necessary to get the data ready for the view.
1:12 And then over in our view method we just create the view model and possibly we
1:18 might give it some form data and other types of things,
1:20 this was a real simple example,
1:22 so it just does its own internal work and returns itself as a dictionary.
1:25 The home/index.html and Flask takes it from there.
1:30 I really, really like this design pattern.
1:32 It might seem a little disjointed but look at how simple and clean that view method
1:38 on the right here is it just does a couple of things, and you know when
1:43 you get to that point that the data is already validated,
1:45 it's already parsed correctly and so on.
1:48 So you'll see we can take a lot of the challenges of data transformation,
1:51 of parsing that might get stuck directly into a view method and
1:55 we'll put it over in these classes, and then we can test these classes separately.
1:59 Right? We could create an instance of a view model
2:02 an IndexViewModel for example and then go and inspect it in pytest and make sure
2:06 everything's working right and so on.
2:07 So it's a really nice separation. Good way to have a class dedicated to knowing what
2:12 it's HTML template needs in terms of data and getting that ready for it to go