HTMX + Flask: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Surveying the non-js-enabled Flask app
Lecture: Concept: View models

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


Talk Python's Mastodon Michael Kennedy's Mastodon