Adding a CMS to Your Flask Web App Transcripts
Chapter: The redirects (our
Lecture: Concept: ViewModels

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Now, before we move on, let's take our code that we've written and make it better make it easier to test
0:07 and make all the different parts that we work with more focused. And we're gonna do that following this thing called a view model pattern.
0:15 Now the website, the data driven website, has been using view models all over the place because that was how it was built
0:20 But we just started from there and we had it on the CMS thing. So you might not have noticed this idea of a view model. So what is this? Well,
0:28 it's most useful when you're accepting user input. You have an HTML form. People are filling it out. They hit, save goes back to the website.
0:36 That data has to be synchronized back to Python. You know what they type into the form Are all the required fields there?
0:43 Maybe there's conversions. They typed in a string. You got to convert it to a number or a date or something like that.
0:48 So the idea of the view model is we're going to take what would otherwise be a really complicated and long method here.
0:56 This is like our CMS requests that we were just messing with. And as we add more validation as we add more logic,
1:04 this just gets longer and longer and it's more complicated and it's harder to test. So what we're gonna do is we're gonna break it into two things.
1:11 The view method that actually handles the request that works with the Web.
1:15 Bremer returns the responses, and then this thing we're calling the view model, this is what we're gonna build.
1:21 This is a separate Python class that knows what data should be exchanged, what is valid, what is invalid. What is the logic to do all that stuff.
1:29 So instead of having that among you method all in one, we're gonna have a view model that it's created by the view method.
1:35 It gets all the data and validates everything and then, as comes back and just helps the view method do its magic.
1:42 Also, this is gonna help with testing if we want to write tests, because it's easy to test the view model outside of the Web framework,
1:49 it typically doesn't need much in terms of what's going on there. Where is maybe the view method is much more complicated gotta start of the website of
1:58 the Web app and get it all up and running before it can actually do its

Talk Python's Mastodon Michael Kennedy's Mastodon